程序开机启动,生成的txt不在程序路径下

环境: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;
    };

验证可行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值