//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.
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.
Bookmarks