环境:win7_64 + VS2012
程序test.exe,设置为开机启动。test.exe中会生成length.txt,xxx.log文件,但是仅指定了length.txt,xxx.log生成的相对路径。
假设test.exe所在目录,C:\Program Files (x86)\Test\test.exe,以生成length.txt代码片段举例说明。
CString filePath = _T("Length.txt");
CStdioFile file;
if(!file.Open(filePath,
CFile::modeWrite | CFile::modeCreate | CFile::osWriteThrough |CFile::shareDenyWrite, NULL))
{
SL_LOG_MSG(_T("文件length.txt打开失败!"));
return;
};
期望length.txt生成路径为C:\Program Files (x86)\Test\length.txt,实际开机启动时,length.txt生成路径为C:\Windows\SysWOW64\length.txt
猜测可能原因:操作系统启动时环境变量path,有默认值C:\Windows\SysWOW64\。系统把相对路径进行了拼接,最终路径成了C:\Windows\SysWOW64\length.txt
修改方法,将相对路径换成绝对路径
CString filePath = _T("Length.txt");
TCHAR cExecPath[MAX_PATH];
if(!GetModuleFileName( 0, cExecPath, sizeof(cExecPath)))
{
return ;
}
CString strExePath(cExecPath);
int nSeparator = strExePath.ReverseFind('\\');
strExePath = strExePath.Left(nSeparator);
filePath.Format(_T("%s\\%s"),strExePath,filePath);
CStdioFile file;
if(!file.Open(filePath,
CFile::modeWrite | CFile::modeCreate | CFile::osWriteThrough |CFile::shareDenyWrite, NULL))
{
SL_LOG_MSG(_T("文件Rodlength.txt打开失败!"));
return;
};
验证可行。