使用“fread”获得意外输出

时间:2015-07-10 09:56:37

标签: c file-io struct fread

有谁可以帮我解决以下代码?

#include<stdio.h>
#include<stdlib.h>
int main()
{
    FILE *fp;
    char another= 'Y';
    struct emp
    {
        char name[14];
        int age;
        float bs;
    }e;
    fp = fopen("Employee.DAT", "wb");
        if (fp == NULL)
    {
        printf("Cannot open file");
        exit(1);
    }
    while (another == 'Y')
    {
        printf("\nEnter name, age and basic salary:");
        scanf("%s %d %f", e.name, &e.age, &e.bs);
        fwrite(&e, sizeof(e), 1, fp);
        printf("Add another record?(Y/N)");

        another=_getche();
    }
    fclose(fp);
    return 0;
}

我正在尝试输入以下内容:
Abc 19 11111 Def 20 22222 Ghi 21 33333
下面代码的输出应该作为上面代码的输入,但我得到下面的输出,如下图所示:
enter image description here

#include<stdio.h>
#include<stdlib.h>
int main()
{
    FILE *fp;
    struct emp
    {
        char name[14];
        int age;
        float bs;
    }e;
    fp = fopen("Employee.dat", "rb");
    if (fp == NULL)
    {
        printf("Cannot open file");
        exit(1);
    }
    while (fread(&e, sizeof(e), 1, fp) == 1);
    printf("%s %d %f\n", e.name, e.age, e.bs);
    fclose(fp);
    return 0;
}

我认为问题在于“恐惧”,但我无法找出问题。

4 个答案:

答案 0 :(得分:3)

while (fread(&e, sizeof(e), 1, fp) == 1);
printf("%s %d %f\n", e.name, e.age, e.bs);
fclose(fp);

您的print语句不在while循环中,因此它只打印最后读取的信息(如果没有成功调用fread,则无效)。

缩进和块有助于编写正确的代码:

while (fread(&e, sizeof(e), 1, fp) == 1) {
  printf("%s %d %f\n", e.name, e.age, e.bs);
}
fclose(fp);

另请注意,这不是一种好的或可靠的序列化数据的方法。结构的布局(甚至是部分,寻找字节序)可能会在不同的编译器和体系结构之间发生变化。

此外,您应该在将文件写入其他代码后关闭该文件。

答案 1 :(得分:1)

请在while语句后删除分号:

while (fread(&e, sizeof(e), 1, fp) == 1) {
  printf("%s %d %f\n", e.name, e.age, e.bs);
}
fclose(fp);

使用分号,循环遍历所有记录并在没有更多记录时停止。现在来自文件的最近(最后)读取记录的printf()打印详细信息。

代码实际上表现为:

while (fread(&e, sizeof(e), 1, fp) == 1)
    ;    
printf("%s %d %f\n", e.name, e.age, e.bs);
fclose(fp);

另外,请在写完记录后立即关闭文件。

答案 2 :(得分:1)

 while (fread(&e, sizeof(e), 1, fp) == 1);
 printf("%s %d %f\n", e.name, e.age, e.bs);

printf语句应该在while循环中。一段时间之后移除;fread将读取直至最后一条记录的end of file,并且循环后printf将打印最后一条记录。

答案 3 :(得分:1)

while (fread(&e, sizeof(e), 1, fp) == 1);

从循环中删除分号,你就完成了!!!!