Fread / fwrite string in C

I have a binary file containing entries. The file structure is as follows:

Structure (see below) Name String Address string

Corresponding structure:

typedef struct{
    char * name;
    char * address;
    short addressLength, nameLength;
    int phoneNumber;
}employeeRecord;
employeeRecord record;

I get the name as such:

char name[50];
printf("\nName:");
fgets(name,50,stdin);
record.nameLength = strlen(name)-1;
record.name = malloc(sizeof(char)*record.nameLength);
strcpy(record.name,name);

I write the structure, name, then address (as mentioned above).

fwrite(&record.name,sizeof(char),record.nameLength,fp);

where fp is the file pointer.

Now I will close the file. However, if I want to read from a file in order to return this data, I believe that I need to read in the structure, read the variable nameLength, malloc enough memory for the name to sit, and then rephrase the name in the variable.

Same:

char *nameString = malloc(sizeof(char)*record.nameLength);
fread(nameString,sizeof(char),record.nameLength,fp);
printf("\nName: %s",nameString);

However, when I try to do this, I do not receive reliable data. Example:

Input name is: Joseph (6 characters)
Output data: 
Name length is 6 (correct), 
Name is   A          (aka garbage)

So it’s obvious that I am doing something wrong. Can anyone help me out?

+3
2

: record.nameLength , fwrite . record.name .

record.nameLength = strlen(name)-1;
...
fwrite(&record.name,sizeof(char),record.nameLength,fp);

record.nameLength = strlen(name);
...
fwrite(record.name,sizeof(char),record.nameLength,fp);

, \0 , , .

char *nameString = malloc(sizeof(char)* (record.nameLength + 1));
fread(nameString,sizeof(char),record.nameLength,fp);
nameString[record.NameLength] = '\0';
+2

, char* fwrite:

fwrite(&record.name,sizeof(char),record.nameLength,fp);

, . Fwrite , char, char.

record.name &record.name, :

fwrite(record.name, sizeof(char), record.nameLength, fp);
+1

Source: https://habr.com/ru/post/1735816/


All Articles