troubleshooting Question

CStdioFile Access Violation

Avatar of Ingo Foerster
Ingo Foerster asked on
ProgrammingMicrosoft DevelopmentC++
11 Comments1 Solution464 ViewsLast Modified:
Hello,
I use in my software CStdioFile. It has worked now for many years but now I get messages that the software will cause Access Violation messaged on growing systems with Windows 7 and Windows 8. I have change the function from CStdioFile to CFile for testing and the access violation do not happen again. But CFile is not good for text.

CStdioFile method:
void CPixbyteHelpers::WriteLogFile(CString nLine){

	CString logFile = theApp.appHelpers.GetSpecialFolderPath(2);

	UINT tFlags;

	if(theApp.appHelpers.PixFileExists(logFile)){
		tFlags = CFile::modeWrite | CFile::shareDenyNone;
	}else{
		tFlags = CFile::modeCreate | CFile::modeWrite | CFile::shareDenyNone;
	}

	CStdioFile f(logFile, tFlags);
	f.SeekToEnd();

	f.WriteString(nLine);
	f.WriteString(_T("\n"));

	f.Close();
}

The CFile method:

void CPixbyteHelpers::WriteLogFile(CString nLine){

	CString logFile = theApp.appHelpers.GetSpecialFolderPath(2);

	HANDLE hFile = CreateFile(logFile,
			GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
			NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);




	if (hFile == INVALID_HANDLE_VALUE)
	{
	   AfxMessageBox(_T("Couldn't create the file!"));
	}
	else
	{
	   // Attach a CFile object to the handle we have.
	   CFile myFile(hFile);
	   myFile.SeekToEnd();

	   static const TCHAR sz[] = _T("\n");

	   // write string
	   myFile.Write(nLine.GetBuffer(nLine.GetLength()), nLine.GetLength());
	   nLine.ReleaseBuffer();
	   myFile.Write(sz, sizeof(sz));
	   

	   // We can call Close() explicitly, but the destructor would have 
	   // also closed the file for us. Note that there's no need to 
	   // call the CloseHandle() on the handle returned by the API because 
	   // MFC will close it for us.
	   myFile.Close();
	   Sleep(100);
	}

}

Anybody here who know (or have an idea) why this access violation happen and why not with the CFile? Anybody know how to write with the CFile method text to a textfile?
ASKER CERTIFIED SOLUTION
Zoppo

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 11 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 11 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros