[英]Saving a txt file into a folder in the same folder as the cpp file in C++
我想制作一个程序,可以将文本文件保存到与cpp
文件位于同一文件夹中的文件夹中,而无需记下完整路径,因为cpp
文件的位置可能会更改。
例子:
我的cpp
位于桌面上一个名为CppFileLocation
的文件中: C:\\Users\\user\\Desktop\\CppFileLocation\\file.cpp
我希望它将文本文件保存到名为CppFileHistory
的文件夹中: C:\\Users\\user\\Desktop\\CppFileLocation\\CppFileHistory\\textfile.txt
它应该可以在不写入完整路径的情况下工作: cpp
文件中的C:\\Users\\user\\Desktop\\CppFileLocation
。
我试过这个:
#include <cctype>
#include <iostream>
#include <string>
#include <fstream>
#include <ctime>
using namespace std;
#pragma warning(disable : 4996)
int main()
{
string filename = "textfile.txt";
ofstream saveloc;
saveloc.open("\\CppFileHistory\\" + fileName);
saveloc << "this is some text.\n";
saveloc.close();
}
感谢您的阅读。
尝试这个:
saveloc.open(".\\CppFileHistory\\" + fileName);
与点.
但我不能保证工作。 因为应该将 C++ 程序编译为可执行文件,然后运行该可执行文件。 当可执行文件运行时,您基本上可以自由选择其“当前工作目录”。 上面代码所做的是,从当前工作目录.
,找到一个子目录CppFileHistory
,并在其中打开fileName
。
您在问题中发布的内容在我看来您将在CppFileLocation
下运行可执行文件。 因此,我建议进行上述更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.