c++文件I/O仅在IDE中运行时工作(Visual c++ Express 2010)
C++ File I/O Works Only When Run In IDE (Visual C++ Express 2010)
创建输出文件代码:
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所在的位置,然后使用一些字符串操作,您可以获得文件的目录。
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 链表c++插入,所有情况都已检查,但没有任何工作
- 为什么stream::忽略未按预期工作