在C+;中使用文件IO时,如何更改保存目录+;? 我试图用下面的C++代码制作一个文件。< /P> ofstream myfile; myfile.open("example.txt"); myfile << "Manchester United\n"; myfile.close(); 流myfile的; myfile.open(“example.txt”); myfile
当前工作目录是您正在其中执行的文件夹。如果您的程序在桌面上,但从System32执行,则当前工作目录是System32,而不是桌面 如果需要当前工作目录: 下面是我的建议,使用C++17和std::filesystem,使用它的current_path()函数在C+;中使用文件IO时,如何更改保存目录+;? 我试图用下面的C++代码制作一个文件。< /P> ofstream myfile; myfile.open("example.txt"); myfile << "Manchester United\n"; myfile.close(); 流myfile的; myfile.open(“example.txt”); myfile,c++,file-io,C++,File Io,当前工作目录是您正在其中执行的文件夹。如果您的程序在桌面上,但从System32执行,则当前工作目录是System32,而不是桌面 如果需要当前工作目录: 下面是我的建议,使用C++17和std::filesystem,使用它的current_path()函数 myfile.open(“Examples/example.txt”)使用std::filesystem::current_path获取或设置当前工作目录。这需要一个支持C++17的编译器。如果C++17对您不可用,这里有一系列针对不同操
myfile.open(“Examples/example.txt”)代码>使用std::filesystem::current_path
获取或设置当前工作目录。这需要一个支持C++17的编译器。如果C++17对您不可用,这里有一系列针对不同操作系统的不同方法:工作目录的移动取决于您运行程序的方式,因此如果您每次都希望文件位于特定位置,你不能单靠工作目录。我用了
而不是
,一切都正常工作。谢谢你的帮助@Tedlyni添加了第二个解决方案,显示了“exe dir”和“当前工作dir”
#include <Windows.h>
#include <iostream>
#include <fstream>
#include <filesystem>
int main()
{
std::filesystem::path cwd = std::filesystem::current_path();
std::filesystem::create_directory("Examples");
cwd /= "Examples";
std::filesystem::path filePath = cwd / "example.txt";
std::ofstream oFile(filePath);
oFile << "Manchester United\n";
oFile.close();
std::cout << "output file path: " << filePath;
std::getchar();
return 0;
}
#include <Windows.h>
#include <iostream>
#include <fstream>
#include <filesystem>
int main()
{
char szExePath[MAX_PATH];
GetModuleFileNameA(GetModuleHandle(NULL), szExePath, MAX_PATH);
std::filesystem::path exePath(szExePath);
exePath.remove_filename();
std::filesystem::create_directory("Examples");
exePath /= "Examples";
std::filesystem::path filePath = exePath / "example.txt";
std::ofstream oFile(filePath);
oFile << "Manchester United\n";
oFile.close();
std::cout << "output file path: " << filePath;
std::getchar();
return 0;
}
auto dir = std::filesystem::path(argv[0]).parent_path() / "Examples";