Reputation: 6577
I'm splitting file buffer on newline delimiter using strtok()
function, but the result I'm getting is not what I expected.
patient->fullName = strtok(fileContent, "\n");
patient->dateOfBirth = strtok(NULL, "\n");
patient->height = strtok(NULL, "\n");
patient->waistMeasurement = strtok(NULL, "\n");
patient->weight = strtok(NULL, "\n");
patient->comment = strtok(NULL, "\n");
When I save delimited values into struct members every member displays fine later on except the first one, fullName
. If I got it right it displays address value instead. Here is the output:
Since I'm still not familiar with C, could you please tell me how can I get full name that's actually written in the file in the place of this pointer address?
EDIT:
Creation of fileContent
:
FILE *file = fopen(fileName, "r");
fseek(file, 0, SEEK_END);
long size = ftell(file);
rewind(file);
char *fileContent = malloc(size + 1);
fread(fileContent, size, 1, file);
Patient:
struct Patient
{
char *fullName;
char *dateOfBirth;
char *height;
char *waistMeasurement;
char *weight;
char *comment;
};
struct Patient *patient = malloc(sizeof(*patient));
patient->fullName = malloc(sizeof(NAME_LENGTH));
patient->dateOfBirth = malloc(sizeof(BIRTHDAY_LENGTH));
patient->height = malloc(sizeof(HEIGHT_LENGTH));
patient->waistMeasurement = malloc(sizeof(WAIST_LENGTH));
patient->weight = malloc(sizeof(WEIGHT_LENGTH));
patient->comment = malloc(sizeof(COMMENT_LENGTH));
File content saved in file (it's encrypted though):
Qevms Wqspgmg
49.46.5336.
534,9
84,7
28,6
Li'w jygomrk eaiwsqi hyhi!
Upvotes: 0
Views: 654
Reputation: 755114
Note that the space allocated by the malloc()
calls is all lost by your use of strtok()
— you are leaking. You need to use strcpy()
to copy strings into the allocated space. You need to check that you allocated enough space before you copy. Or you could use the POSIX function strdup()
— patient->fullName = strdup(strtok(fileContent, "\n"));
. (That's a tad risky; I'd usually check the return from strtok()
before passing it to strdup()
— but it makes the point.)
Also, because you're copying pointers to fileContent
, if you read the next line into fileContent
, it will change the values of the strings pointed at by the previous patient
record. Or, when fileContent
goes out of scope and is used for another purpose, the data will change again.
Upvotes: 3