我需要使用fread/fwrite函数来完成任务。我写了下面的代码:
#include <stdio.h>
#include <string.h>
struct rec{
int account;
char name[100];
double balance;
};
int main()
{
struct rec rec1;
int c;
FILE *fptr;
fptr = fopen("clients.txt", "r");
if (fptr == NULL)
printf("File could not be opened, exiting program.\n");
else
{
printf("%-10s%-13s%s\n", "Account", "Name", "Balance");
while (!feof(fptr))
{
//fscanf(fptr, "%d%s%lf", &rec.account, rec.name, &rec.balance);
fread(&rec1, sizeof(rec1),1, fptr);
printf("%d %s %f\n", rec1.account, rec1.name, rec1.balance);
}
fclose(fptr);
}
return 0;
}
clients.txt文件
100 Jones 564.90 200 Rita 54.23 300 Richard -45.00
输出结果
账户 姓名 余额 540028977 Jones 564.90 200 Rita 54.23 300 Richard -45.00╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠ü☻§9x°é -92559631349317831000000000000000000000000000000000000000000000.000000
按任意键继续. . .
我可以使用fscanf(已被我注释掉),但我需要使用fread / fwrite。
- 为什么Jones的账户余额会从一个巨大的数字开始?
- 为什么还有垃圾字符?难道feof不能阻止这种情况吗?
- 使用这种方法或fscanf方法有什么缺点?
如何解决这些问题? 非常感谢您的帮助!