Wednesday, July 3, 2019

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

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

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...