Why can't fopen open a file that exists?

I work in Windows XP using Visual Studio 6 (yes, I know, the old one), building / maintaining the C ++ DLL. I ran into a problem when fopen was unable to open an existing file, it always returns NULL.

I tried:

  • Checking errno and _doserrno, setting both values ​​to zero and then checking them again, both remain equal to zero, and so GetLastError () does not report errors. I know that fopen is not required to install errno when it encounters an error according to the C standard.
  • Hardcoding is a file path that is not relative.
  • I tried on another development machine, which had the same result.

It is really strange that CreateFile works, and the file can be read using ReadFile. We believe this works in release builds, however we also see very strange behavior in other areas of the application, and we are not sure if this is related.

The code below, I do not see anything strange, it looks quite standard for me. The original file has not changed for less than six months.

HRESULT CDataHandler::LoadFile( CStdString szFilePath ) { //Code FILE* pFile; if ( NULL == ( pFile = fopen( szFilePath.c_str(), "rb") ) ) { return S_FALSE; } //More code } 
+6
c ++ windows file-io fopen vc6
source share
5 answers

Answer:

I found the reason too many open file processes cause some recent application updates. They do not change, but this error has been present for some time. I entered the fopen function before a function called _getstream. This is trying to find a thread that is not in use, the function searches for a table of 512 threads. Of course, all 512 where they are used, and other calls to fopen where failing. I used the handle tool from sysinternals to see the number of descriptors used.

+9
source share

Your function has a return type of HRESULT (where 0 is good), but you are returning a boolean value (where 0 is bad). It may not be right ...

+2
source share

Assuming you have a reasonable version of VC6, you have the source code for CRT, and you can go into the fopen call and go all the way to the CreateFile call that the CRT will do. (Get ready for this pretty far!)

+1
source share

put a breakpoint on the fopen line, run it in the debugger, enter " ERR, hr " in the "Watch" window, execute the line and check Look at what the problem is. Most likely, these are access permissions.

0
source share

You already have 512 open files.

We can only store max 512 open files in a VC application. I suggest closing unnecessary files with fclose .

0
source share

All Articles