fame_empathy
fame_empathy

Reputation: 17

reading strings from file to struct array in C

I am trying to read strings from file and add them to my array of structs but when i do i get some random characters at the end of one or two strings.Here is my code for reading strings line by line:

while ((read = getline(&line, &len, fp)) != -1) {
strncpy(&structures[i].id,line,4);   //copies the first four characters to my array of structures
...
}

When i print out the structures[0].id it prints "WW23�" when it should be just "WW23".It does that with couple of strings, although not with all of them. My struct looks like this.

struct observers
{
 char id[13];
 ...
};

It reads from file properly at least it gets the integer values right.

Upvotes: 0

Views: 474

Answers (2)

Amnon Shochot
Amnon Shochot

Reputation: 9356

You probably need to add '\0' as the 5'th character to terminate the string.

Upvotes: 1

sumithdev
sumithdev

Reputation: 331

You are not terminating the string. Add '\0' at the end structures[i].id[4] = '\0'. It should work fine.

Upvotes: 4

Related Questions