1

I'm getting a strange file handle from fopen; the pointer itself isn't NULL, but the file it represents has no size, and feof(file) is already set... what could be causing this?

(I triple checked the file itself, it exists, has data, and the file's permissions are okay... and filename is set to "source/test_file.object.txt")

bool tagFile(const char * filename){
    FILE * file = fopen(filename, "r");
    if(file == NULL){                        // file is not NULL
        printf("   Couldn't open the file %s", filename);
        return false;
    }
    int size = fseek(file, 0, SEEK_END); // size is 0
    rewind(file);
    while(feof(file)){

        ....  // never executes because feof(file) fails
    }
}
0x002cc410  // value of 'file' in the debugger
    _ptr=0x00000000 <Bad Ptr> 
    _cnt=0 
    _base=0x00000000 <Bad Ptr>
    _flag = 1
    _file = 3
Anne Quinn
  • 10,856
  • 7
  • 40
  • 83
  • 1
    Could you try `fseek(file, 0L, SEEK_END);` and `size = ftell(file);` instead of only `int size = fseek(file, 0, SEEK_END);`? In order to rewind, could you try `fseek(file, 0L, SEEK_SET);` – Paulo Dec 23 '15 at 15:39
  • How do you call `tagFile`? – cadaniluk Dec 23 '15 at 15:41
  • 1
    I feel like a total fool... the problem was a lot simpler than I thought. `feof(file)` should be `feof(file) == 0` the things you spot 2 minutes after asking... thank you for the help though! – Anne Quinn Dec 23 '15 at 15:48
  • 1
    Oh, God. I missed that part. You can still use !feof(file) (that's the way I use it). – Paulo Dec 23 '15 at 15:59

1 Answers1

0

The most common cause of this is simply opening a file which is empty. There are no bytes to read so EOF is immediate, but the file exists so fopen can't return NULL.

MSalters
  • 159,923
  • 8
  • 140
  • 320