-1

我正在尝试读取名为的文件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;
}

编译后我得到File opened successfully!File read failed. 我的内容pp.txt是34.5。谁能告诉我我哪里出错了?

4

5 回答 5

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()调用读取了该数字并将文件指针移到该数字之外。现在第二个电话找不到号码并失败。

于 2013-09-03T08:48:01.733 回答
1

删除f=fopen("pp.txt","r");第一if条语句之前的内容,并删除fscanf(f, " %f", &x);其相应if语句之前的内容。

于 2013-09-03T08:45:23.160 回答
1

打开文件一次

读取一次值(除非您想跳过浮点数)。

退出前关闭文件。

如果文件为 NULL,请不要关闭文件。-> 将导致未定义的行为

#include<stdio.h>
#include<stdlib.h>
int main()
{

     FILE *f;
     float x;


     f = fopen("pp.txt", "r");

     if(f == NULL) // remove fopen here, already did that
     {
          fprintf(stderr, "Sorry! Can't read %s\n", "TEST1.txt");
     }
     else
     {
           printf("File opened successfully!\n");

           if (fscanf(f, " %f ", &x) != 1) // you were reading 2 times
           {    
                fprintf(stderr, "File read failed\n");
                fclose(f); // close the file before exiting
                return EXIT_FAILURE; 
           }
           else
           {
                printf("The contents of file are: %f \n", x);
           }

           fclose(f);
     }

     return 0;
}
于 2013-09-03T08:56:07.223 回答
0

你的模式中有一个空格" %f ",我猜你的文件没有这些空格。

于 2013-09-03T08:54:06.867 回答
0

问题:

  1. 打开文件两次。资源泄漏。
  2. 您的操作系统可能有浮点数而不是点的逗号分隔符。
  3. 您没有检查第一次 scanf 的结果

对主题启动者的建议:在开始编码之前在纸上创建算法(流程图)。你会有很多简单的错误,因为你没有想象你的代码在做什么。你只是试图让它在不理解的情况下工作。

于 2013-09-03T08:48:20.673 回答