Why am I not able to get handle of file?
Hello,
I've a code snippet. Please follow the comments.
Code:
//Create a directory if it doesn't exist
if ( !PathFileExists("C:\\TestDir") )
{
CreateDirectory("C:\\TestDir", NULL);
}
//Create a batch file in the directory
CFile cfBatchFile( "C:\\TestDir\\TestBatch.bat", CFile::modeCreate| CFile::modeRead | CFile::modeWrite );
//Write 'C:\\windows\\system32\cmd.exe" ipconfig>C:\\TestDir\\Test.txt in the batch file
cfBatchFile.Write( "\"C:\\windows\\system32\cmd.exe\" ipconfig>C:\\TestDir\\Test.txt", MAX_PATH );
cfBatchFile.Close();
//ShellExecute runs "C:\\TestDir\\TestBatch.bat" and generates output for 'ipconfig' and redirects it to text file "C:\\TestDir\\Test.txt"
if ( ShellExecute(NULL, "open", "C:\\TestDir\\TestBatch.bat", NULL, NULL, SW_HIDE) > (HINSTANCE)32)
{
CFile* pcfTxt = NULL;
//Trying to open 'C:\\TestDir\\Test.txt' for reading BUT CRASH HAPPENS HERE (unhandled Exception)
pcfTxt = new CFile(_T("C:\\TestDir\\Test.txt"), CFile::modeRead | CFile::shareDenyNone);
INT nLogTxtLen = pcfTxt->GetLength();
}
In Debug mode (without a Debug point), the crash is shown at
pcfTxt = new CFile(_T("C:\\TestDir\\Test.txt"), CFile::modeRead | CFile::shareDenyNone);
But if I place a debug point at :
pcfTxt = new CFile(_T("C:\\TestDir\\Test.txt"), CFile::modeRead | CFile::shareDenyNone);
and then continue, no crash arises.
I guess the issue is something to do with the handle of 'C:\\TestDir\\Test.txt' file.
How could I rectify this.
Is some Sleep() required to wait for the handle to be available.
Replies would be appreciated.
Thanks
Re: Why am I not able to get handle of file?
When you use the debugger with a breakpoint, time passes, so maybe the shellexecute is still using/generating your textfile. You are trying to open it with shareDenyNone, but if the file is locked by someone else, shareDenyNone will probably fail. For testing purposes you could add a sleep of a few seconds between the execute and your fileopen. If this helps, it could be a locking problem.
Re: Why am I not able to get handle of file?
Thanks for replying.
Yes, that's exactly the case.
But is using Sleep() mandatory ? Don't I have any other option to wait for the handle.
Thanks.
Re: Why am I not able to get handle of file?
Code:
SHELLEXECUTEINFO stExec = {0};
stExec.cbSize = sizeof(SHELLEXECUTEINFO);
stExec.fMask = SEE_MASK_NOCLOSEPROCESS;
stExec.lpVerb = "open";
stExec.lpFile = "somefile.bat";
stExec.nShow = SW_HIDE;// or SW_SHOW
if (ShellExecuteEx (&stExec))
{ // Program running
WaitForSingleObject (stExec.hProcess, INFINITE);
}
else
{
// error
}
CloseHandle (stExec.hProcess);
This ShellExecuteEx function waits until it is done executing. After it is done you can open your textfile without any problems (I assume ;) ).