简体   繁体   中英

Reading data from file to struct using fread

I'm writing a piece of code and a part of it is reading "records" from file to n-length array, n given as an argument. Records in file have constant length(in this case 1024) and contain only numerics, spaces and lower letters. Each record is terminated with \\n. I'm using following structure to keep one record:

typedef struct{
char rec[1024];
} record;

And Code for extracting n of them and storing in n-length array of records is written this way:

record * recs=malloc(n*sizeof(record));
size_t read=fread(recs,sizeof(record),(size_t)n,f);

When I checked output of this operations it turns out that first element of array recs contains all of the records, second all but first and so on instead of keeping one at each element of array. I'm kind of lost, because i thought that it should store each record in different element of array. As suggested, I'm also providing code for opening a file and printing elements of array:

if((f=fopen(argv[2],"r"))==NULL){
        perror("error opening file\n");
        exit(1);
    }

for(int i=0;i<(int)read;i++){
        printf("record number %d\n %s\n",i,recs[i].rec);
    }

The problem is that your records rec isn't a zero terminated string.

So printing using %s shows all records because the printing will just continue until it sees a '\\0' .

So either make sure to add a zero-termination in each rec or use another way of printing than %s .

BTW: If there isn't any zero-termination inside recs you actually have undefined behavior.

This little program mimics the problem:

#include <stdio.h>

struct r {
    char c[1];
};

int main(void) {
    int i;
    struct r recs[4] = {{'a'}, {'b'}, {'c'}, {'\0'}};
                                      //       ^^^^^
                                      //       Just to stop printing here
    for (i=0; i<3; i++)
    {
        printf("%d %s\n", i, recs[i].c);
    }

    return 0;
}

Output:

0 abc
1 bc
2 c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM