c - 如何读取文件的第一个数字?

标签 c text file-io

我正在尝试从文件中读取数字并将这些数字放入数组中。现在文件如下所示:

100

0 1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17 18 19

20 21 22 23 24 25 26 27 28 29

显然第一个数字是数组的大小。当我尝试测试读取时,我得到了 8。这是我的代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE * filePtr;
    int firstNum;
    filePtr = fopen("array,dat", "r");
    if(filePtr!=NULL)
    {
    fscanf(filePtr, "%d", &firstNum);
    fclose(filePtr);
    }
    printf("size: %d", firstNum);


    return 0;
}

这是我得到的结果:

size: 8
Process returned 0 (0x0)   execution time : 0.012 s
Press any key to continue.

那么我怎样才能得到我想要的正确数字以及为什么它显示8?

最佳答案

由于拼写错误 array,dat -> array.dat,您的程序无法打开该文件。因此,它只会打印未初始化变量 firstNum 的内容,其中可能包含任何垃圾值。

如果您编写错误处理,例如:

if(filePtr==NULL)
{
  printf("Could not open file %s", fileName);
  return 0; // no point in continuing execution after this
}

关于c - 如何读取文件的第一个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33095595/

相关文章:

java - 我需要一种优雅的方式来从处理中排除特定的单词

c - 如何在 C 程序中定义具有大小为 N 的随机值的复数 vector

php - 在 PHP 中查找多个 TXT 文件中的特定文本

file - VBA:文件打开到 PDF 页面

text - 解释没有分隔符的文本的含义

C# 如何在组合框文本中添加值?

java - 在 Java 的 try-catch 方法中实现 while 循环

从函数更改结构数组(从文件读取)

java - 将 C 指针转换为 Java

c - 一个简单的递归函数打印奇怪的东西