Hello every1
I was making this program of a phone directory to store contacts and all their information in C. I made use of structure and then copied the data of the structure to a file.
the structure is

struct phdata
{
       char name[20],add[20];
       int phno;
}ph[20];

the problem i am facing is that when i run the program a second time, i need to know the no. of records already in the file so that new records are added after that. For this purpose i am having to use a separate file which contains the Number of records already in the file. Cant i achieve this only by using a single file rather than 2 separate files?

why not just put the number of records in the file followed by all the records. Or just read one record at a time until end-of-file -- you don't need the number beforehand.

why not just put the number of records in the file followed by all the records. Or just read one record at a time until end-of-file -- you don't need the number beforehand.

Hmm...I dont really get you can you be more explainatory?
How do i read till "EOF" in case of reading structure from a file. I use the following statement to read from file.

fread(&ph, sizeof(ph), 1, fp);

where ph is the structure name and fp the file pointer

since it is a binary file

int numValidRecords = ???;
// write out the file
fwrite(&numValidRecords,sizeof(int),1,fp);
fwrite(&ph,sizeof(ph),1,fp);

// read the file
int numValidRecords = 0;
fread(&numValidRecords,sizeof(int),1,fp);
fread(&ph, sizeof(ph), 1, fp);

or

// write the file
for(int i = 0; i < NumValidRecords; i++)
    fwrite(&ph[i],sizeof(ph[0]),1,fp);

// read the file
int i = 0;
while ( i < 20 && fread(&ph[i], sizeof(ph[0]), 1, fp) > 0)
   ++i;
commented: real help +2

Thnx a ton! I never knew I could use the same file for storing different types of data. thnks. I tried your first method and it worked just fine.

Problem Statement: File Handling in C/C++
On the basis of the given scenario create a file Expenses.txt, Open the file and copy into another Expenses2.txt, Also show output on screen
A college has announced the total budget of 50,000Rs.for each game. Games are done four times in a year. Take expenses as an input from user.
Calculate the average expenses for a game:

1. If the expenses greater than 80% show as” Very Expensive”.
2. If the expenses are greater than 60% and less than 80% than show “Expensive ”
3. If the expenses are greater than 50% and less than 60% than show “Less Expensive ”
4. If the expenses are greater than 40% and less than 50% than show “Not Costly”.
5. If the expenses are less than 40% than show “Best

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.