Wednesday 3 July 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...