因为在程序中如果你使用如下方法写文件的话:
std::ofstream out("cache.txt");
out << "test" << std::endl;
out.close();
一般情况下, 它会写到当前应用程序所在目录, 但是如果在程序的某个地方, 调了SetCurrentDirectory("E:\\"); 那么当调到上面的代码时就会将文件写到E:\\cache.txt, 这一般不是自己所期望的事。总结:获取当前exe所在的的绝对路径, 使用函数GetModuleFileName:
#include<windows.h>
string get_current_exe_path()
{
char module_path[MAX_PATH];
if ( GetModuleFileName( NULL, module_path, MAX_PATH ) )
{
return string(module_path);
}
else
{
return string("");
}}
然后再利用这个函数的返回值, 得到上层目录即可。