0

我尝试读取我的FILE*fp 指向的文件,我想知道文件的结尾在哪里。因此我使用fseek();在文件的末尾,我想从我的structure data.

void printData(FILE *fp)
{
    struct data tmp;
    fseek(fp,0,SEEK_END);
    while(fread(&tmp,sizeof(struct data),1,fp) > 0)
    {
        puts("test2");
        printf("Vorname: %s\n",tmp.vorname);
        printf("Nachname: %s\n",tmp.name);
        printf("Adresse: %s\n",tmp.adresse);

    }
}

这就是我的结构的定义方式:

struct data
{
    char name[30];
    char vorname[20];
    char adresse[50];
};

我的问题是,while 循环甚至没有执行一次。我忘记了什么吗?

4

5 回答 5

3

fseek(fp,0,SEEK_END) positions the file pointer at the end of the file (starting point end of the file offset 0), when you then try to read from the file fread of course doesn't read anything.

instead open the file in append mode and fwrite the number of records, these will be appended to the file.

于 2013-06-28T08:41:04.950 回答
0

After seeking to the end-of-file you won't be able to read anything. If you just want to know the file size, you can mybe use fstat() instead, or you do the fseek() after reading what you wanted to read, thad depends on what you're trying to achieve.

于 2013-06-28T08:43:26.573 回答
0

您正在寻找文件的开头,因为您将偏移量设置为 0。这听起来不像您想要做的,但另一方面寻找到最后然后尝试读取也会失败. 我很困惑。:/

难道你的意思是fwrite(),而不是`fread()?不太可能,因为其余代码在 I/O之后打印结果,这对于读取来说是合乎逻辑的,但对于写入来说是不合逻辑的。

提供更多信息会很有帮助,例如您的文件已打开以及运行程序时包含的内容。

于 2013-06-28T08:32:22.880 回答
0

fread() is used for reading contents from file not for writing.

Use fwrite() for writing contents to file.

Like:

fwrite(&tmp , 1 , sizeof(struct data) , fp );

Read more about: fread() and fwrite()

于 2013-06-28T08:47:25.460 回答
0

fread 中的第三个变量“1”实际上表示要读取的项目数,而您只是在阅读一项。请参阅 fread 文档: http: //pubs.opengroup.org/onlinepubs/009696899/functions/fread.html

于 2013-06-28T08:34:49.543 回答