开发者

fflush fails on Visual C++ 2010

开发者 https://www.devze.com 2023-02-25 09:46 出处:网络
I\'m trying to run some code but fflush() with the error: Invalid file descriptor. File possibly closed by a different thread

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
 开发者_如何学C   {
        fread(g_tpd_list, file_stat.st_size, 1, fhandle);
        fflush(fhandle);
        fclose(fhandle);
    }


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消