任何人都可以請幫我解決下面的代碼嗎?使用「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
爲下面的代碼的輸出應該將上述代碼的輸入,但我得到了下面的輸出圖像中下面附:
#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;
}
我認爲這個問題是用「的fread」,但我無法找出問題。
您是否檢查過fread的返回值實際上是1?您的打印語句不在while循環中,因此它將以任一方式執行。 –
當'fread'讀取一個無效的條目時,'while'循環只會停止讀取,而且 - 意外! - 是將要打印的那個。刪除該行末尾的';'。 – usr2564301
我認爲你必須在寫完後關閉文件。同時檢查你的while循環,因此刪除;之後... – TryinHard