繁体   English   中英

将txt文件保存到C++中cpp文件所在文件夹的文件夹中

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM