我正在尝试读取名为 pp.txt
的文件的内容并在命令行上显示其内容。我的代码是:
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *f;
float x;
f=fopen("pp.txt", "r");
if((f = fopen("pp.txt", "r")) == NULL)
{
fprintf(stderr, "Sorry! Can't read %s\n", "TEST1.txt");
}
else
{
printf("File opened successfully!\n");
}
fscanf(f, " %f", &x);
if (fscanf(f, " %f ", &x) != 1) {
fprintf(stderr, "File read failed\n");
return EXIT_FAILURE;
}
else
{
printf("The contents of file are: %f \n", x);
}
fclose(f);
return 0;
}
编译后,我得到文件打开成功!文件读取失败
。我的 pp.txt
内容是 34.5。谁能告诉我哪里出错了?
最佳答案
问题是您执行了某些函数两次。 这里:
f=fopen("pp.txt", "r");
if((f = fopen("pp.txt", "r")) == NULL)
{
fprintf(stderr, "Sorry! Can't read %s\n", "TEST1.txt");
}
这里:
fscanf(f, " %f", &x);
if (fscanf(f, " %f ", &x) != 1) {
fprintf(stderr, "File read failed\n");
return EXIT_FAILURE;
}
将它们更改为
f=fopen("pp.txt", "r");
if(f == NULL)
{
fprintf(stderr, "Sorry! Can't read %s\n", "TEST1.txt");
return EXIT_FAILURE;
}
和
r = fscanf(f, " %f", &x);
if (r != 1)
{
fclose(f); // If fscanf() fails the filepointer is still valid and needs to be closed
fprintf(stderr, "File read failed\n");
return EXIT_FAILURE;
}
不要忘记定义 int r;
您收到错误是因为您的第一个 fscanf()
调用读取了该数字并将文件指针移到了该数字之外。现在第二次调用找不到号码并失败。
关于c - C 无法显示文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18587711/