简体   繁体   中英

How do I check if a file pointer is valid?

I am using fseek and fread on a FILE * like this:

void CAudioDataItem::finalizeItem_ReadEncodedBytesWithoutDecoding(FILE* uFile, CLog* uLog, double& uTimeReadEncodedBytes)
{
    //t.start();
    fseek(uFile, iFirstByteToRead, SEEK_SET);
    fread(&m_EncodedBytes[0], sizeof(unsigned char), m_lLenEncodedBytes, uFile);
    //t.stop();

However, it doesn't work, the bytes are all 0.

I suspect that somewhere in my app, the FILE pointer gets invalid or something else becomes wrong with this pointer.

How could I check if this file handle is still valid and "usable"?

Here is a screenshot:

在此处输入图像描述


Here is a screenshot of a situation where it still works. As one can see, the _Placeholder is different. What does this _Placeholder mean?

在此处输入图像描述

If the question is on C++ as one of the tags imply,

There's typically no way to tell if the pointer dangles , ie, points to memory that no longer holds the object the pointer is supposed to point to.

from Effective Modern C++ , in the introduction to Chapter 4 - Smart Pointers , page 117.

If it's on C, then from the comments we know the same point holds for C.

As regards _Placeholder=0x00000000 when it doesn't work vs _Placeholder=0x1bc715bf when it works, I'm not sure why the numbers (which are memory addresses, I believe) are those that you see; maybe _Placeholder=0x00000000 means that something in the program has set the pointer to nullptr , but the point is that once that (or something else which invalidates the pointer) has happened, you can't do anything to query it.

The only way to go about this is to surrender to the evidence that the program has a bug that results in undefined behavior and try to debug it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM