这是 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);
}
这是输入和输出:
如何更正此代码以使其打印全名?
最佳答案
问题出在“编写器”应用程序中,甚至在执行实际写入之前。
当你从用户那里得到数据时
scanf("%S %d %f", e.name, &e.age, &e.bs);
您使用格式
%S
(大写字母“S”。格式说明符是 区分大小写 !)。正如我们在 printf
man page 中所读到的那样S
(Not in C99, but in SUSv2.) Synonym for ls. Don't use.
这将我们带到
%ls
以下列方式描述的格式说明符s
[...] If an l modifier is present: The constwchar_t *
argument is expected to be a pointer to an array of wide characters. Wide characters from the array are converted to multibyte characters
谈Windows source我们有:
S
Opposite-size character string, up to first white-space character (space, tab or newline). [...]
When used withscanf
functions, signifies wide-character array; when used withwscanf
functions, signifies single-byte-character array [...]
因此,基本上,您是从 stdin 读取字符并将它们转换为 宽字符 .在这种情况下,每个字符都需要
sizeof(wchar_t)
.可能在您的系统中,此大小为 4。您需要的只是
%s
格式说明符。并且由于您的 name
数组大小为 40,我建议使用scanf("%39s", e.name );
从用户那里获取名称。这样最多可以写入 39 个字符,第 40 个字符保留给字符串终止符
'\0'
.
关于c - 用C读取和写入二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61957595/