我正在尝试从文件中读取数字并将这些数字放入数组中。现在文件如下所示:
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/