Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;文件I/O仅在IDE中运行时有效(Visual C+;+;Express 2010)_C++_File_Io - Fatal编程技术网

C++ C++;文件I/O仅在IDE中运行时有效(Visual C+;+;Express 2010)

C++ C++;文件I/O仅在IDE中运行时有效(Visual C+;+;Express 2010),c++,file,io,C++,File,Io,创建我的输出文件的代码: ofstream outFile; outFile.open(filename, ios::trunc); 当我从IDE运行该程序时,输出文件将在项目目录中创建,并且一切正常 但是,当我通过在windows资源管理器中实际打开.exe版本来运行程序时,不会创建任何文件,即使 outFile.is_open() 返回true 我该如何解决这个问题?或者文件是在我不知道的地方创建的?因为我希望它出现在工作目录中 注意:我没有使用文件名的绝对路径,它被设置为“out.t

创建我的输出文件的代码:

ofstream outFile;
outFile.open(filename, ios::trunc);
当我从IDE运行该程序时,输出文件将在项目目录中创建,并且一切正常

但是,当我通过在windows资源管理器中实际打开.exe版本来运行程序时,不会创建任何文件,即使

outFile.is_open() 
返回true

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

注意:我没有使用文件名的绝对路径,它被设置为“out.txt”之类的内容


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

要获取exe文件的当前路径(而不是像
GetCurrentDirectory
那样的当前工作目录),您需要该函数

它可以这样使用:

#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;
}
#包括
#包括
#包括
常量字符*模块_路径()
{
静态字符p[FILENAME_MAX];
memset(&p,0,文件名_MAX);
GetModuleFileName(0,p,文件名\u MAX);
返回p;
}
std::string目录(仅限常量std::string&p)
{
返回p.substr(0,p.find\u last\u of(“/\”);
}
int main(int argc,char*argv[])
{
std::string cpath=module_path();
std::string new_file=directory_only(cpath)+“\\somefile.txt”;

std::您能在文件名中指定完整路径吗?您可以使用procmon之类的工具查看文件的创建位置。@David W到目前为止,我一直在将文件名设置为“output.txt”之类的内容。如果is_open返回true,则我会怀疑由于目前未知的原因正在意外的位置创建文件:)。仍然建议尝试使用procmon。程序认为它是从哪里运行的?GetCurrentDirectory返回什么?如果从visual studio运行,则文件是在工作目录中创建的,则当您从发布目录执行文件
out\u文件应在发布目录中创建。发布目录是否具有写入权限?是否可以发布更多代码,特别是文件名字符串的值