-
Binary FIle I/O
Code:
void create_customer()
{
FILE *customer_fp;
customer_indexed indexed_array[FILE_SIZE]; //255
customer_record new_record;
int i;
customer_fp = fopen("test.bin", "wb");
printf("Input customer first name: ");
scanf("%s", new_record.first_name);
printf("Input employee last name: ");
scanf("%s", &new_record.last_name);
fwrite(&new_record, sizeof(new_record), 1, customer_fp);
fprintf(customer_fp, "\n");
fclose(customer_fp);
}
I am trying to write this to a binary file. It wont be implemented using scanf later, its just to see if its working for now.
I have another file to read the binary file, but it will only allow me to add one entry. I am calling the function twice in main.
Any suggestions?
Thanks
-
You don't need the "\n" since it's a binary file - no need to seperate the records with anything.
Reading and writting structures in this way means that your are using fixed sized records in the file. This means you must have fixed char arrays in custormer_record for first_name and last_name. If thats true, then it looks good (except for the "\n").
Just as a good programming habbit, I like to use sizeof() on the structure type rather than the structure variable (ie. sizeof(custormer_record)) to avoid accidentally using sizeof() on a pointer.
gg
-
Yes I do have fixed sizes for them.
I took out the \n, I thought that was why it wasnt putting the data into the file.
Still, nothing appears in the file.
Code:
customer_record new_record;
int i,j;
FILE *fp;
fp = fopen("test.bin" ,"rb");
while(1 == fread(&new_record, sizeof(customer_record),1,fp))
printf("%s %s\n" ,new_record.first_name, new_record.last_name);
fclose(fp);
That is the printing of the binary file.
-
When you open the file, the file pointer for writting is at the beginning of the file. So the second time you call your create_customer() function, you are overwritting the last record you wrote. You will want to move the file pointer to the end of the file, or open the file for appending with "a+" in the mode.
gg
-
Thanks for the help.
I open the file with an editor instead of using the read function.
It seems like only the first scanf is inputed into the file.
-
>>open the file for appending with "a+"
Don't forget binary mode is also required.