准备
一个需要修改批量文件路径的文件 一段需要添加的文字 一个C++程序
展示
首先准备好add.txt和pathlist.txt 在未使用之前,每个文件都是下面这样 在使用程序之后
代码如下
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
void readLine(vector<string> &tmps) {
ifstream fin;
string line;
fin.open("pathlist.txt");
if(fin) {
while(!fin.eof()) {
getline(fin, line);
tmps.push_back(line);
}
}
fin.close();
tmps.pop_back();
}
void read(string path, string &tmp) {
string line;
ifstream fin;
fin.open(path);
if(fin) {
while(!fin.eof()) {
getline(fin, line);
tmp.append(line);
tmp.append("\n");
}
}
if(tmp.size() > 0) {
tmp.erase(tmp.size()-1);
}
fin.close();
}
void printtext(string path, string text, string copyr) {
ofstream fout;
fout.open(path);
if(fout) {
cout << path << " : success" <<endl;
fout << copyr;
fout << text;
}
else {
cout << path << " : error" <<endl;
}
fout.close();
}
int main() {
vector<string> lines;//存储文件路径
string copyr;//存储添加的字符串
string text;//存储文件原来的字符串
//获取文件路径
readLine(lines);
//获取需要添加的字符串
read("add.txt", copyr);
for(string line : lines) {
text.clear();
//获取文件原先的字符串
read(line, text);
//把需要添加的字符串和原先的字符串整合在一起
printtext(line, text, copyr);
}
return 0;
}