从文件读取到数组

时间:2013-03-13 20:39:01

标签: c io fread

我正在尝试从文件中读取。我正在使用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看起来像这样:

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

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

3 个答案:

答案 0 :(得分:1)

以下给出的代码在for循环中足够

fread(person[j], sizeof(struct Person), 1, fp);

答案 1 :(得分: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

答案 2 :(得分:0)

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