1

我正在尝试从文件中读取。我正在使用 fread(),但我不确定我是否正确地处理了这个问题。我想创建一个结构数组并继续从文件“f-reading”到数组中,如下所示:

//Get size of file
struct stat st;
stat(document, &st);
int size = st.st_size;

//Create appropriate array size of structs

struct Person person[size];

for(j = 0; j < size; j++) {
    fread(person[j].name, 1, 16, fp); //each name is truncated to 15 bytes on the file
    fread(person[j].text, 1, 24, fp);  //text is truncated to 24 on the file
}

结构人看起来像这样:

struct Person {
    char name[16];
    char text[24];
};

我正确使用 fread() 吗?谢谢你。

4

3 回答 3

1

下面给出的代码在 for 循环中就足够了

fread(person[j], sizeof(struct Person), 1, fp);
于 2013-03-13T20:45:29.443 回答
0

您应该检查 fread 函数调用是否成功地从数据流中读取了预期的字节数:

//Get size of file
struct stat st;
int name_bytes_read, text_bytes_read; // If using C11, use size_t instead
stat(document, &st);
int size = st.st_size;


//Create appropriate array size of structs

struct Person person[size];

for(j = 0; j < size; j++) {
    name_bytes_read = fread(person[j].name, 1, 16, fp); //each name is truncated to 15 bytes on the file
    if (name_bytes_read != 16) { 
      fputs ("Error reading name record", stderr); 
      exit(-1);
    }
    text_bytes_read = fread(person[j].text, 1, 24, fp);  //text is truncated to 24 on the file
    if (text_bytes_read != 24) {
      fputs ("Error reading text record", stderr);
      exit(-1); }
}

进一步阅读:http ://www.thegeekstuff.com/2012/07/c-file-handling

于 2013-03-13T21:01:01.147 回答
0

通过 sizeof(struct Person) 增加 j 以避免 fread 问题或者您可以使用 feof 检查文件结尾

于 2013-03-13T21:31:25.880 回答