用C读写二进制文件

问题描述 投票:0回答:1

这些是2个单独的应用程序。

  • [在第一个中,我试图在名为emp.bin的二进制文件中存储员工的详细信息,例如姓名,年龄和薪水。
  • 在第二个应用程序中,我尝试查看文件的内容,但仅显示第一个字符代替名称。

我尝试分别打印每个字符,结果是名称中每个字母后面有3个空字符'\ n',这就是为什么它不打印第一个字符之后的原因。

“写入”应用程序代码:

//Receives records from keyboard and writes them to a file in binary mode
#include <stdio.h>

int main()
{
    FILE *fp;
    char another = 'Y';
    struct emp
    {
        char name[40];
        int age;
        float bs;
    };
    struct emp e;
    fp = fopen("emp.bin", "wb");
    if (fp == NULL)
    {
        puts("Cannot open the file.");
        return 1;
    }
    while(another == 'Y')
    {
        printf("Enter the employee name, age and salary: ");
        scanf("%S %d %f", e.name, &e.age, &e.bs);
        while(getchar() != '\n');
        fwrite(&e, sizeof(e), 1, fp);
        printf("Add another record? (Y/N)");

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

“读取”应用程序代码:

//Read records from binary file and displays them on VDU
#include <stdio.h>
#include <ctype.h>

int main()
{
    FILE *fp;
    struct emp
    {
        char name[40];
        int age;
        float bs;
    } e;
    fp = fopen("emp.bin", "rb");
    if (fp == NULL)
    {
        puts("Cannot open the file.");
        return 1;
    }
    while (fread(&e, sizeof(e), 1, fp) == 1)
    {
        printf("\n%s \t %d \t $%.2f\n", e.name, e.age, e.bs);
    }
    fclose(fp);
}

以下是输入和输出:enter image description hereenter image description here

我如何更正此代码以使其打印出全名?

c pointers scanf binaryfiles file-pointer
1个回答
0
投票

甚至在执行实际写入之前,问题就出现在“ writer”应用程序中。

当您从用户那里获得数据时

scanf("%S %d %f", e.name, &e.age, &e.bs);

您使用格式%S(大写字母“ S”。格式说明符为区分大小写!)。正如我们在printf man page]中所看到的

S

(不是在C99中,而是在SUSv2中。)ls的同义词。不要用

这将导致我们进入以以下方式描述的printf格式说明符

s

[...]如果存在l修饰符:const wchar_t *参数应为指向宽字符数组的指针。数组中的宽字符将转换为多字节字符

因此,基本上,您是从stdin

读取字符并将其转换为wide chars。在这种情况下,每个字符占用四个字节。

您需要的只是%ls格式说明符。并且由于您的%s数组的大小为40,因此我建议使用

name

从用户那里获取名称。这样,最多可以写入39个字符,这是字符串终止符

scanf("%39s ", e.name ); 保留的第40个字符。
© www.soinside.com 2019 - 2024. All rights reserved.