版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012911202/article/details/85129935
程序中调用CFile/CStdioFile打开文件准备写文件,同时手动打开该文件,程序崩溃。跟代码发现,CFile/CStdioFile打开文件失败,指针无效,程序崩溃。
实例一
void MyClass::WriteInFile(CString filePath,int *nLength)
{
CStdioFile file;
//增加CFile::shareDenyWrite模式,程序写length.txt时,同时可以手动打开length.txt。否则,file.open失败,file是无效指针,程序会崩溃。
file.Open(filePath,
CFile::modeWrite | CFile::modeCreate | CFile::osWriteThrough |CFile::shareDenyWrite, NULL);
//file是无效指针时,该行出错
file.SeekToBegin();
CString str = _T("hello world!");
file.WriteString(str);
file.Close();
}
查询MSDN,share模式有多种(见截图),可根据需要,设不同模式,
实例二
//增加share模式,这样程序写log文件时,同时手动可以打开。否则,程序会崩溃。
//fopen_s没有share模式,用_fsopen代替。
FILE* fp=NULL;
char* szPath = "C:\|Intel\\log.txt";
string strTime=GetTime();
//fopen_s(&fp, szPath, "a+");
if( (fp = _fsopen( szPath, "a+", _SH_DENYWR )) == NULL )
{
fclose(fp);
return;
}
fwrite(strTime.c_str(), strTime.size(), 1, fp);
fwrite(" ", 1, 1, fp);
...
fwrite("\n", 1, 1, fp);
fclose(fp);
_fsopen更多信息参见MSDN