开发者

Where/How does the string pointed by a pointer gets stored in a file?

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="R开发者_开发百科avi 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_name pointer - 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.


The emp_name member is a pointer to char. Therefore, the pointer itself will be stored in the file, instead of the string it points to. That string will be lost, and reading back the pointer from the file will be meaningless if the program is restarted in-between.

You can work around that problem by storing a array of char in your EMPLOYEE structure instead of a pointer. However, in that case, you won't be able to directly assign it a value anymore, and will have to use something like strncpy() instead:

e1.emp_id = 2240;
strncpy(e1.emp_name, "Ravi Shekhar", sizeof(e1.emp_name));
// Add a null terminator in case emp_name wasn't large enough.
e1.emp_name[sizeof(e1.emp_name) - 1] = '\0';
e1.emp_salary = 10000;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜