c - C 无法显示文件内容

标签 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;
}

编译后,我得到文件打开成功!文件读取失败。我的 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/

相关文章:

c - 指向传递给函数的指针

file - 比较两个文件中的相同行,其中顺序无关紧要

c++ - 如何从文件c++中读取每一行

python - 读取具有指定换行符的文件

c++ - 线路抑制状态错误 LNK2005 _main 已在 lua.obj 中定义

c - 制作 : *** No rule to make target

c# - 创建新的 C# 文件时命名空间错误?

linux - direct_io失败的原因

java - 删除 JComboBox 内的文件

c - Ansi C 运行时性能全局变量与局部变量