Friday 22 April 2016

How to count the number of integers in a file in C?




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

#include
#include

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 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



Answer



while(!feof(file)){
fscanf(file, "%d", &array[count]);
count++;

}


Instead of checking for eof, you need to check the returncode of fscanf():



while(fscanf(file, "%d", &array[count]) == 1)
count++;


But it would be better to build in some safety too, like:




#define NUM_ITEMS 1000

int array[NUM_ITEMS];

int main(int argc, char* argv[]){
{
FILE* file;
int i, count = 0;


file = fopen(argv[1], "r");

if (!file) {
printf("Problem with opening file\n");
return 0; // or some error code
}

while(count < NUM_ITEMS && fscanf(file, "%d", &array[count]) == 1)
count++;


fclose(file);

for(i=0; i printf("a[%d] = %d\n", i, array[i]);
}

return 0;
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...