The following code sample writes a structure variable of type EMPLOYEE to a file and then using fread reads the structure back in another variable.
int main()
{
EMPLOYEE e1,e2;
FILE *fptr;
e1.emp_id=2240;
e1.emp_name="Ravi Shekhar";
e1.emp_salary=10000;
fptr=fopen("c:\\employee.emp","w+b");
if(fptr == NULL)
{
printf_s("\n\t cannot open file. . .");
return 1;
}
printf_s("%d records written successfully. . .",fwrite(&e1,sizeof(EMPLOYEE),1,fptr));
fseek(fptr,0,SEEK_SET);
fread(&e2,sizeof(EMPLOYEE),1,fptr);
printf_s("\nID = %d\nName = %s\nSalary = %10.2lf",e2.emp_id,e2.emp_name,e2.emp_salary);
fclose(fptr);
_getch();
return 0;
}
My question is where and how the name string pointed by the e1.emp_name(a char* type) gets stored in the binary file.
Thanks.
It doesn’t get stored at all.
What gets stored is the binary content of
char *emp_namepointer – the address of a static string"Ravi Shekhar". Since you write that data and read it back again during the same execution session of your program, this pointer value remains valid. I.e. when you read it from file, it still points to the same static string"Ravi Shekhar"it was pointing to originally.If you split your program into two programs (one does the writing and another does the reading), you’ll discover that the “reader” program can no longer “read” the string from file, since it is not really there. You’ll simply read a binary pointer value, which points nowhere inside the “reader” program.