麻烦从二进制文件读取数据到struct数组

时间:2017-04-14 05:22:58

标签: arrays struct

我有一个二进制文件,其中包含一些使用struct数组输入的数据。

但是,当我尝试读回我的值并显示它们时,只打印第一个值,然后打印垃圾值。

我哪里出错了?

这是代码:

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

struct eagleEmployees{
    char userName[16];
    char psswd[16];

};

int main()
{
    int i;
    struct eagleEmployees data[3];

    FILE* fptr;

    fptr = fopen("eEmployees.bin", "wb");

    for(i=0; i<3; i++){

        printf("\nEnter client name %d: ", i+1);
        scanf(" %s", data[i].userName);

        printf("\nEnter client password %d: ", i+1);
        scanf(" %s", data[i].psswd);
   }

   i++;

   fwrite(data, sizeof(struct eagleEmployees), 3, fptr);

   fclose(fptr);

   // I close the file above and reopen for reading below.

   FILE *f;
   f = fopen("eEmployees.bin", "rb");

   for(i=0; i<3; i++){

   fread(data,1,sizeof(struct eagleEmployees), f);

   printf("\n %s \t %s",data[i].userName, data[i].psswd);

   }

   fclose(f);

   return 0;
}

0 个答案:

没有答案