c++文件I/O仅在IDE中运行时工作(Visual c++ Express 2010)

C++ File I/O Works Only When Run In IDE (Visual C++ Express 2010)

本文关键字:c++ 工作 Visual Express 2010 运行时 文件 仅在 IDE      更新时间:2023-10-16

创建输出文件代码:

ofstream outFile;
outFile.open(filename, ios::trunc);

当我从IDE中运行程序时,输出文件将在项目目录中创建,并且一切正常。

然而,当我通过在windows资源管理器中实际打开。exe来运行程序时,没有创建任何文件,即使

outFile.is_open() 

返回true。

如何解决这个问题?或者文件是在我不知道的地方创建的?因为我希望它显示在工作目录中。

注意:我没有使用文件名的绝对路径,它被设置为"out.txt"之类的东西。

编辑:我已经使用了GetCurrentDirectory,并且发现当我从windows资源管理器运行。exe时,它使用我的文档和设置作为当前目录。所以现在我必须问,我如何让它使用。exe的目录作为工作目录?

要获得exe文件的当前路径(而不是GetCurrentDirectory所做的当前工作目录),您将需要GetModuleFileName函数。

可以这样使用:

#include <windows.h>
#include <string>
#include <iostream>
const char* module_path()
{
    static char p[FILENAME_MAX];
    memset(&p, 0, FILENAME_MAX);
    GetModuleFileName(0, p, FILENAME_MAX);
    return p;
}
std::string directory_only(const std::string& p)
{
    return p.substr(0, p.find_last_of("/\"));
}
int main(int argc, char* argv[])
{
    std::string cpath = module_path();
    std::string new_file = directory_only(cpath) + "\somefile.txt";
    std::cout << "full exe: " << cpath << std::endl;
    std::cout << "directory: " << directory_only(cpath) << std::endl;
    std::cout << "new_file = " << new_file << std::endl;
    return 0;
}

GetModuleFileName将获得当前exe所在的位置,然后使用一些字符串操作,您可以获得文件的目录。