【发布时间】:2020-09-09 10:42:22
【问题描述】:
这是 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);
}
这是输入和输出:
如何更正此代码以使其打印全名?
【问题讨论】:
-
干得好,简明扼要地说明问题并显示演示问题的简短代码。第一个问题很好。
-
我没有在我的回答中提到它,因为它可能是一个错字(因为我在编辑时注意到它)但是当你说_“3个空字符'\n'”_有一个错误:
\n是换行符; nul 字符是\0(字符串终止符),它实际上是你得到的(我复制了你的问题)。 -
while(getchar() != '\n');会在文件提前结束的情况下导致无限循环。
标签: c pointers scanf binaryfiles file-pointer