做算法實驗,代碼查重,需要讀取文件,c++讀取文件過於蛋疼了,還是記錄下把
步驟:
- 使用ifstream打開文件流
- 重定向輸入輸出流到文件
- 讀取數據/寫入數據
- 輸入輸出流回到控制檯
#include <bits/stdc++.h>
using namespace std;
/*
* @function readfile : 將文件作爲行字符串讀取進lines
* @param filepath : 文件路徑
* @param lines : 接收文件行的字符串數組
* @return : ----
*/
void readfile(string filepath, vector<string>& lines)
{
ifstream ifs(filepath); // 打開文件流
streambuf *ori_in = cin.rdbuf(); //保存原來的輸入輸出方式
cin.rdbuf(ifs.rdbuf()); // 流重定向
while(getline(cin,filepath)) lines.push_back(filepath); // 讀取文件行
ifs.close(); // 關閉流
cin.rdbuf(ori_in); //回到控制檯的標準輸入輸出
}
/*
* @function writefile : 將lines數組中字符串作爲行寫入文件
* @param filepath : 文件路徑
* @param lines : 寫入內容 字符串數組
* @return : ----
*/
void writefile(string filepath, vector<string>& lines)
{
ofstream ofs(filepath); // 打開文件流
streambuf *ori_out = cout.rdbuf(); //保存原來的輸入輸出方式
cout.rdbuf(ofs.rdbuf()); // 流重定向
for(int i=0; i<lines.size(); i++) cout<<lines[i]<<endl; // 讀取文件行
ofs.close(); // 關閉流
cout.rdbuf(ori_out); //回到控制檯的標準輸入輸出
}
int main()
{
vector<string> lines;
readfile("1.txt", lines);
writefile("2.txt", lines);
return 0;
}
寫入後