C++ 将文件路径与文件名组合为字符串

ali*_*ati 6 c++

我想在我的 C++ 代码中读取一些输入文件,并且想将输入文件的路径定义为字符串,然后将其与文件名组合。我怎样才能做到这一点?(输入路径+文件名.dat)

Vla*_*sky 7

#include <filesystem> //C++ 17
#include <iostream>

namespace fs = std::filesystem;
using namespace std;

void main()
{
    string dir("c:\\temp");
    string fileName("my_file.txt");
    
    fs::path fullPath = dir;
    fullPath /= fileName;
    cout << fullPath.c_str() << endl;
}
Run Code Online (Sandbox Code Playgroud)


Ste*_*evo -1

你会使用类似的东西:

string path ("yourFilePath");
string filename ("filename");
Run Code Online (Sandbox Code Playgroud)

然后您可以像这样打开该文件:

ifstream inputFileStream;
inputFileStream.open(path + fileName);
Run Code Online (Sandbox Code Playgroud)

根据您的要求,您必须决定在阅读时使用格式化还是未格式化的输入。我会读这个以获取更多相关信息。

串联引用自:C++ string concatenation 读取引用自:C++ read and write with files