我想使用C创建一个文本文件,每次运行代码时都会继续添加分数而不删除最后一条记录。不幸的是,当我运行代码时,它所做的只是运行printf
语句并创建一个文件score.txt
,但不会写入任何内容,而只是崩溃。
以下是代码:
int main()
{
FILE *score;
score = fopen("score.txt", "w");
fclose(score);
int s;
char n;
printf("You got a high score!\nPlease enter score: ");
scanf("%d", &s);
printf("\nPlease enter your name: ");
scanf("%s", &n);
fprintf(score,"%d", s);
fprintf(score,"%d", n);
printf("\nData Stored into score.txt\n");
return 0;
}
答案 0 :(得分:4)
这里有多个问题。
在fclose(score);
之后,您尝试使用fprintf(score,"%d", s);
。为什么?也许您想在fclose(score);
;
return 0
始终对fopen()
的返回值进行成功检查。另外,根据您的要求,keep on adding score every time the code is run without deleting the last record
您需要{em>追加模式中的fopen()
。详细了解模式及其使用情况here。
scanf("%s", &n);
错了。这里你想要的是一个数组,而不是一个char
。考虑将char n;
更改为char n[32];
或其他内容。 [注意:一旦n
为数组,请将scanf()
更改为scanf("%s", n);
]
fprintf(score,"%d", n);
错了。不要使用不兼容的格式说明符。对于字符串,它应该是%s
。 [即使在您的情况下,n
也是char
。格式说明符不应该是%d
。]
答案 1 :(得分:2)
上面给出的代码几乎没有问题。
下面给出的代码提供了一种附加到文件的正确方法。
FILE *score;
char name[100];
int nScore;
// Open the file
score = fopen("score.txt", "a+");
if(!score)
{
printf("Failed to open");
return 1;
}
// Get user inputs
printf("You got a high score!\nPlease enter score: ");
scanf("%d", &nScore);
printf("\nPlease enter your name: ");
scanf("%s", name);
//Write to file
fprintf(score, "Name: %s Score: %d\n", name, nScore);
// Close the file
fclose(score);
printf("\nData Stored into score.txt\n");
return 0;
答案 2 :(得分:0)
另请注意,名称n
无法存储为char
。它必须是char []
或char *
。这可能是造成你崩溃的原因,虽然@SouravGhosh也是正确的 - 基本上你的代码中至少有两个错误。
E.g。
char n[80]; // or any other reasonable value, or learn dynamic memory allocation
scanf("%s", n);