无法在C中显示文件的内容

时间:2013-09-03 08:41:51

标签: c file file-io

我正在尝试读取名为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。谁能告诉我哪里出错?

5 个答案:

答案 0 :(得分: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()调用会读取该数字并将文件指针移到其后面。现在第二个电话找不到号码而失败。

答案 1 :(得分:1)

在第一个f=fopen("pp.txt","r");语句之前移除if,并在相应的fscanf(f, " %f", &x);语句之前移除if

答案 2 :(得分:1)

打开文件一次

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

退出前关闭文件。

如果文件为NULL,请不要关闭文件。 - &GT;会导致未定义的行为

#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;
}

答案 3 :(得分:0)

问题:

  1. 两次打开文件。资源泄漏。
  2. 您的操作系统可能有浮点数的逗号分隔符而不是点。
  3. 您没有检查第一次扫描的结果
  4. 关于主题入门者的建议:在开始编码之前在纸上创建algorythm(流程图)。你会遇到很多简单的错误,因为你无法想象你的代码在做什么。你只是试着让它在不理解的情况下工作。

答案 4 :(得分:0)

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