我有这段代码,它从main函数的第一个参数中读取文件,并计算其中存储的整数数量。
#include<stdio.h>
#include <sys/wait.h>
#include <stdlib.h>
int array[100000];
int count = 0;
int main(int argc, char* argv[]){
FILE* file;
int i;
file = fopen(argv[1],"r");
while(!feof(file)){
fscanf(file, "%d", &array[count]);
count++;
}
for(i=0; i<count; i++){
printf(" \n a[%d] = %d\n",i,array[i]);
}
return 0;
}
执行此文件时的输出为:
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5
a[5] = 6
a[6] = 7
a[7] = 8
a[8] = 9
a[9] = 10
a[10] = 0
为什么计数器的值比预期多1?
我的输入文件使用"./a.out /home/ghost/Desktop/file.txt",内容如下:
1 2 3 4 5 6 7 8 9 10
while(!feof(file))
,这是不正确的!你应该阅读fscanf()
的文档,然后使用while (fscanf(file, "%d", array[count++]) == 1);
。此外,绝对不需要全局变量。 - Iharob Al Asimifscanf
的返回值(这是你应该总是做的事情),你就能够发现/避免这个bug了。 - hydemain()
中定义,它将具有与整个程序相同的生命周期。 - Iharob Al Asimi