Where / How is the string indicated by the pointer stored in the file?

The following code example writes a structure variable of type EMPLOYEE to a file, and then, using fread, reads the structure back into 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 indicated by e1.emp_name (type char *) is stored in a binary file.

Thank.

+3
source share
2 answers

It is not stored at all.

char *emp_name - "Ravi Shekhar". , . , "Ravi Shekhar", .

( , ), , "" "" , , , "".

+4

emp_name char. , , . , , .

, char EMPLOYEE . strncpy():

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;
+3

All Articles