I am using CStdioFile::Read
in an MFC application, and in the MFC sourc code I noticed that an exception is thrown in the following condition:
filetxt.cpp in function UINT CStdioFile::Read
if ((nRead = (UINT)fread(lpBuf, sizeof(BYTE), nCount, m_pStream)) == 0 && !feof(m_pStream))
AfxThrowFileException(CFileException::genericException, _doserrno, m_strFileName);
Questions:
- What are the possible reasons for this exception to be triggered?
- Could this be due to file permissions, locking, or disk errors?
- Are there any specific scenarios where
fread
fails butfeof
remains false? - How should I handle this exception properly to differentiate between different failure scenarios?
I understand that nRead == 0
means no bytes were read, but since feof(m_pStream)
is false, it suggests that EOF has not been reached.
Also, before calling CStdioFile::Read
, we have checked that the file is open using CStdioFile::Open
function too.
I am using CStdioFile::Read
in an MFC application, and in the MFC sourc code I noticed that an exception is thrown in the following condition:
filetxt.cpp in function UINT CStdioFile::Read
if ((nRead = (UINT)fread(lpBuf, sizeof(BYTE), nCount, m_pStream)) == 0 && !feof(m_pStream))
AfxThrowFileException(CFileException::genericException, _doserrno, m_strFileName);
Questions:
- What are the possible reasons for this exception to be triggered?
- Could this be due to file permissions, locking, or disk errors?
- Are there any specific scenarios where
fread
fails butfeof
remains false? - How should I handle this exception properly to differentiate between different failure scenarios?
I understand that nRead == 0
means no bytes were read, but since feof(m_pStream)
is false, it suggests that EOF has not been reached.
Also, before calling CStdioFile::Read
, we have checked that the file is open using CStdioFile::Open
function too.
1 Answer
Reset to default 0Q:
What are the possible reasons for this exception to be triggered?
A:
Most likely disk I/O errors, failure to read from a mistreated CDRom, damaged hard drive, network errors, removing an USB stick while you're reading from it and so on.
Q:
Could this be due to file permissions, locking, or disk errors?
A:
See answer above. Most likely not from file permissions, because you wouldn't have been able to open file file in the first place. Locking? Unlikely, but I'm not quite sure here.
Q:
Are there any specific scenarios where fread fails but feof remains false?
A:
IMO only errors, see questions above.
Q:
How should I handle this exception properly to differentiate between different failure scenarios?
A:
It depends on your use case. But most likely not. You read from a file, you get an error, well then handle it, for example display an error message.
_doserrno
? Should be included in the exception report. – Richard Critten Commented Feb 4 at 10:47std::exception
. That's enough reason to stick with what's there. – j6t Commented Feb 4 at 11:21