1

I'm trying to run some code but fflush() with the error:

 Invalid file descriptor. File possibly closed by a different thread

Here is the relevant part of the code:

    fhandle = fopen("dbfile.bin", "rbc");
    /* There is a valid dbfile.bin file - get file size */
    _fstat(_fileno(fhandle), &file_stat);
    printf("dbfile.bin size = %d\n", file_stat.st_size);

    g_tpd_list = (tpd_list*)calloc(1, file_stat.st_size);

    if (!g_tpd_list)
    {
        rc = MEMORY_ERROR;
    }
    else
    {
        fread(g_tpd_list, file_stat.st_size, 1, fhandle);
        fflush(fhandle);
        fclose(fhandle);
    }
forsvarir
  • 10,749
  • 6
  • 46
  • 77
chustar
  • 12,225
  • 24
  • 81
  • 119
  • Usually you'd flush the file when you're writing to it (to clear the write buffer)...you shouldn't need to flush it for what you're doing, what effect are you expecting? – forsvarir Apr 12 '11 at 05:05
  • i'm not expecting anything. this part of the code is provided by the instructor as is. – chustar Apr 12 '11 at 05:09

2 Answers2

1

Oddly, it seems like this behaviour is caused by the fact that you're passing the 'c' mode into your fopen call. The help says this about the flag:

Enable the commit flag for the associated filename so that the contents of the file buffer are written directly to disk if either fflush or _flushall is called

So I'm not sure why it's causing it to behave the way it is. However, if you remove it, the fflush call works. It could be that this flag is undoing the ability for fflush to clear the read buffer and making it always attempt to clear the write buffer.

forsvarir
  • 10,749
  • 6
  • 46
  • 77
0

fflush is supposed to flush the write buffer. By standard C It is an undefined behavior to call fflush on read-only streams. It seems that Microsoft CRT treats such call as an error. You do not need the fflush in your case anyway.

UPD: According to clarifications from comments my suggestion is not completely correct. Microsoft CRT has a special meaning for fflush on read streams. It clears the effect of ungetc

Denis K
  • 1,448
  • 1
  • 10
  • 17
  • Not actually what the VS help says 'If the stream is open for input, fflush clears the contents of the buffer. fflush negates the effect of any prior call to ungetc against stream' – forsvarir Apr 12 '11 at 05:14
  • @forsvarir, sure, that is a feature I was not aware of. However, there are no calls to ungetc in this code sample – Denis K Apr 12 '11 at 05:19