I am read from a file like this:
#include <stdio.h>
int main() {
FILE *fp = fopen("sorted_hits", "r+");
while(!feof(fp)) {
int item_read;
int *buffer = (int *)malloc(sizeof(int));
item_read = fread(buffer, sizeof(int), 1, fp);
if(item_read == 0) {
printf("at file %ld\n", ftell(fp));
perror("read error:");
}
}
}
This file is big and I got the “Bad file descriptor” error sometimes. “ftell” indicates that the file position stopped when error occurred.
I don’t know why it is “sometimes”, is that normal? does the problem lie in my code or in my hard disk? How to handle this?
perrorprints whatever is inerrnoas a descriptive string.errnogets set to an error code whenever a system call has an error return. But, if a system call DOESN’T fail,errnodoesn’t get modified and will continue to contain whatever it contained before. Now iffreadreturns 0, that means that either there was an error OR you reached the end of the file. In the latter case,errnois not set and might contain any random garbage from before.So in this case, the “Bad file descriptor” message you’re getting probably just means there hasn’t been an error at all. You should be checking
ferror(fp)to see if an error has occurred.