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

时间:2015-02-23 08:11:11

标签: c++

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

3 个答案:

答案 0 :(得分:1)

#include <filesystem>
#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 :(得分:0)

你会使用类似的东西:

string path ("yourFilePath");
string filename ("filename");

然后你可以这样打开文件:

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

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

Cocatenation引自:C++ string concatenation 阅读参考:C++ read and write with files

答案 2 :(得分:-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;
}