二进制文件读取不正确

时间:2019-05-07 03:14:18

标签: c

我是C语言的新手,正在尝试读写结构到.dat文件。添加数据时,我在.dat文件中看到了字符。但是,我无法读取数据,并且在每次出现结构时都应该输出“ val”时,我的代码什么也不输出。

我看过很多资料,但是我找不到我的代码与那些资料有何不同。

https://www.geeksforgeeks.org/readwrite-structure-file-c/ 该网站最初用于了解如何执行此操作。

Read/Write to binary files in C 我用它来查看如何修复我的代码,但是解决方案没有帮助。

我尝试在while循环中更改语句。

struct person
{
    int id;
    char lastName[15];
    char firstName[15];
    char age[4];
};


int main(void) {
  //create new file
  FILE *fp = fopen("file.dat", "wb+");

  struct person a = {10, "Smith", "John", 25};
  fwrite(&a, sizeof(a), 1, fp);

  struct person b = {2, "Ali", "Jon", 12};
  fwrite(&b, sizeof(b), 1, fp);

 struct person c = {19, "Walter", "Martha", 82};
  fwrite(&c, sizeof(c), 1, fp);

  struct person p; 
  while(fread(&p, sizeof(p), 1, fp))
  printf("val");
}

当前,它应打印3个“ Val”,因为dat文件中添加了三个人。但是,什么都没有打印出来。

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

写完记录后,文件指针(“光标”,即您正在读取/写入的位置)位于文件的末尾。在尝试从文件读取之前,必须使用rewind()fseek()fsetpos()将该位置重新设置为文件的开头。

答案 1 :(得分:0)

如果您想读回并打印,请尝试在使用fpos_tfgetpos()写入文件之前捕获文件的开始位置。稍后在写入文件后,使用fsetpos()设置初始位置,然后使用fget()读取内容并进行打印。检查修改后的代码如下-

#include<stdio.h>
#include<stdlib.h>

struct person
{
    int id;
    char lastName[15];
    char firstName[15];
    char age[4];
};


int main(void) {
  //create new file
  FILE *fp = fopen("file.dat", "wb+");
  fpos_t position;


  struct person a = {10, "Smith", "John", "25"};
  fwrite(&a, sizeof(a), 1, fp);

  struct person b = {2, "Ali", "Jon", "12"};
  fwrite(&b, sizeof(b), 1, fp);

  struct person c = {19, "Walter", "Martha", "82"};
  fwrite(&c, sizeof(c), 1, fp);

  fseek(fp, 0, SEEK_SET);

  struct person p; 
  while(fread((void *)&p, sizeof(p),1,fp)==1)
  {
    printf("%d\n",p.id);
    printf("%s\n",p.lastName);
    printf("%s\n",p.firstName);
    printf("%s\n",p.age);    
    printf("\n");
  }
}