Click here to Skip to main content
15,889,648 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
char CurrentPath[MAX_PATH] = {0};
GetModuleFileName(NULL,CurrentPath,MAX_PATH);
char BaseNameA[MAX_PATH] = {0};
GetBaseNameFromPath(CurrentPath,BaseNameA);
if(hFile==NULL)
{
    hFile = CreateFile(CurrentPath,GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
    if(hFile==INVALID_HANDLE_VALUE)
        MessageBox(0,"hFile Failed!",0,0);
}


Hello!

The code above is failing randomly (sometimes it works perfectly, other times it reports "hFile Failed!"). I don't quite understand why it fails at times.

Perhaps I should use C-libraries for opening the current process's file?

Perhaps someone knows a more reliable solution?

Again all I'm trying to do is open the local file of the current process I'm in.

Thank you!
Posted
Comments
Richard MacCutchan 28-Jul-13 3:22am    
You could help yourself to diagnose the problem by calling GetLastError() when it fails, and displaying the actual error code.
pasztorpisti 28-Jul-13 12:28pm    
:thumbs up: good idea! Something people always forget... :-)
Richard MacCutchan 28-Jul-13 13:07pm    
The worrying thing is that if it doesn't fail during testing they probably release it in that state.

1 solution

Try using FILE_SHARE_READ|FILE_SHARE_WRITE as the 3rd parameter.
 
Share this answer
 
Comments
H.Brydon 28-Jul-13 0:19am    
I think you mean FILE_SHARE_READ (the file in question is the executable for the current program/programme).
+5 though
pasztorpisti 28-Jul-13 0:28am    
Thank you! I think FILE_SHARE_WRITE should not hurt, with this we tell windows that we allow other CreateFile calls to open the file for whatever operations (even for writing) while we are reading its contents.
[no name] 28-Jul-13 9:50am    
Richard MacCutchan's suggestion should confirm if this required I think.
pasztorpisti 28-Jul-13 12:26pm    

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900