[英]c++ combine path of file as a string with file name
我想在我的 C++ 代碼中讀取一些輸入文件,我想將輸入文件的路徑定義為一個字符串,然后將其與文件名組合。 我怎樣才能做到這一點? (輸入路徑 + 文件名.dat)
#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;
}
你會使用類似的東西:
string path ("yourFilePath");
string filename ("filename");
然后你可以像這樣打開文件:
ifstream inputFileStream;
inputFileStream.open(path + fileName);
根據您的要求,您必須決定在閱讀時是使用格式化輸入還是未格式化輸入。 我會閱讀本文以獲取有關此的更多信息。
Cocatenation 引用自: C++ string concatenation讀取引用自: C++ read and write with files
嘗試以下任何代碼:
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.