-
writing to file
I have written the code to write all the records in typedef struct CONTACT people
It writes the first file ok but when you add a second entry it prints the 'file write error'which I don't understand as the condition is not equal to 1.
cheers :confused: :confused:
code below
Code:
/* Save the list. Writes file to disc*/
void save(void)
{
FILE *fp;
int n;
int dex;
int index;
if((fp=fopen("maillist.txt", "wb"))==NULL) /* binary file*/
{
printf("Cannot open file.\n");
return;
}
for(index=0;index<MAX;index ++) /* write spaces with underscorce in file*/
{
for(dex=0; dex < strlen(people[index].address1); dex++)
{
if (people[index].address1[dex]==' ')
people[index].address1[dex]='_';
}
}
for(n=0; n<MAX; n++)
if(*people[n].surname)
if(fwrite(&people[n], sizeof(CONTACT), n, fp)!=1)
printf("File write error.\n");
fclose(fp);
}
Code tags added by moderator
-
> printf("File write error.\n");
Do you get more information if you do
perror("File write error.\n");
-
Code:
if(fwrite(&people[n], sizeof(CONTACT), n, fp)!=1)
The error is in this line.
first of all, a bit of explanation about the fwrite function.
First of all, let me state that fwrite is IMHO optimized to deal with arrays.
The first argument takes in an address, this can be an address of a variable, or an address of an array. In your code, this is correct.
second argument takes in the size of the data that you wish to write to the file. Again, you got this correct.
Third argument takes in the number of data that you are writing to the file. Unless you are passing in an array, in which case you would pass in the number of elements in the array, you would then pass in 1 as the value for this argument. I actually suspect, since your for loop starts from 0, that if you were to check the data you stored in the file, that you actually only wrote the second data in your array. When your for loop hits n == 2, you are telling fwrite to write two data when you are only passing in [b]one/b] data. This is where I think the error is.
fourth argument is of course the FILE pointer. No problems here!
As a last point, are you sure you want to treat a text file as a binary file? if all your data are strings, it may still be slightly readable, but I think you may have gibberish all over the place, especially if you ever try to write a struct with datatypes other than strings...