C++将文件路径和文件名合并为字符串

6

我想在我的C++代码中读取一些输入文件,我希望将输入文件的路径定义为一个字符串,然后与文件名组合。我该怎么做?(Input_path + filename.dat)


1
请添加你目前所写的代码。 - Refilon
一种方法是在调用 ifstream 之前进行组合(在 ifstream 中进行组合不可行)。这个方法很有效。无论如何,感谢您的建议。 - Ali Kefayati
3个回答

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;
}

-1
你可以使用类似以下的代码:
string path ("yourFilePath");
string filename ("filename");

你可以像这样打开文件:

ifstream inputFileStream;
inputFileStream.open(path + fileName);

根据您的需求,您将不得不决定在读取时是否使用格式化或未格式化的输入。我建议阅读this以获取更多相关信息。
串联引用自:C++字符串串联 读取引用自:C++文件读写

`string name; // To hold the file name//Write the path of the folder in which your file is placed string path = "C:\Users\Faisal\Desktop\Programs\"; cout << "Enter the file name: ";getline(cin, name);// Open the file.file.open(path + name.c_str());// Test for errors.` - Faisal Qayyum
我遇到了错误:[Error] no matching function for call to 'std::basic_ifstream<char>::open(std::basic_string<char>) - Faisal Qayyum
这个答案现在已经过时了。请查看下面Vlad的答案:https://dev59.com/3Yjca4cB1Zd3GeqPsB5P#68504328 - Casey

-1

尝试使用以下任何代码:

#include <iostream>
#include <string>
#include <fstream>
int main() {

  std::string filepath = "D:/location/";
  filepath+= "filename.dat";
  std::ifstream fp;
  fp.open(filepath.c_str(),std::ios_base::binary);

  ....PROCESS THE FILE HERE
  fp.close();

    return 0;
}

或者

#include <iostream>
#include <string>
#include <fstream>
int main() {

   std::string filepath = "D:/location/";
  std::ifstream fp;
  fp.open((filepath+"filename.dat").c_str(),std::ios_base::binary);

 ...............

  fp.close();
    return 0;
}

或者使用std::string::append

#include <iostream>
#include <string>
#include <fstream>
int main() {

 std::string filepath = "D:/location/";
  std::ifstream fp;
  fp.open((filepath.append("filename.dat")).c_str(),std::ios_base::binary);



  fp.close();
  return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接