I have this code which reads a file from the first argument to the main and counts the number of integers stored in it.
#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; } The output when I execute this file is
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 Why is the value of count one greater than expected?
My input file using "./a.out /home/ghost/Desktop/file.txt" is as follows :
1 2 3 4 5 6 7 8 9 10
while(!feof(file))that is wrong! You should read the documentation offscanf()and then you would come up with thiswhile (fscanf(file, "%d", array[count++]) == 1);Also, absolutetly no need for global variables.fscanf(something you should always do).arrayis much safer as a global variable than a local variable in the stack, with that size... And usingmallocin a snippet like this would just distract from the real issue. So using globals makes sense in the context.main()it will have the same lifetime as the whole program.