我试图读取一个名为的文件的内容,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;
}
Run Code Online (Sandbox Code Playgroud)
编译后我得到了File opened successfully!File read failed.我的内容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");
}
Run Code Online (Sandbox Code Playgroud)
和这里:
fscanf(f, " %f", &x);
if (fscanf(f, " %f ", &x) != 1) {
fprintf(stderr, "File read failed\n");
return EXIT_FAILURE;
}
Run Code Online (Sandbox Code Playgroud)
改变他们
f=fopen("pp.txt", "r");
if(f == NULL)
{
fprintf(stderr, "Sorry! Can't read %s\n", "TEST1.txt");
return EXIT_FAILURE;
}
Run Code Online (Sandbox Code Playgroud)
和
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;
}
Run Code Online (Sandbox Code Playgroud)
别忘了定义int r;
您收到错误是因为您的第一个fscanf()调用读取了数字并将文件指针移到了它之外.现在第二个呼叫找不到号码而失败.