Outline:
Base

ifstream {Read}
1 2 3 4 5 6 7 8
| string readFile(string file) { ifstream tmp(file.c_str()); string fileContents((istreambuf_iterator<char>(tmp)), istreambuf_iterator<char>());
tmp.close(); return fileContents; }
|
ofstream {Write}
1 2 3 4 5 6
| void writeFile(string bodyStr) { ofstream os("dst.csv", ostream::app); os << bodyStr; os.close(); }
|
STL–ostream_iterator:
ostream_iterator属于I/O流STL适配器,用于获取一个元素,同时保存在缓冲器中,可以供Cout输出。如果把cout看做成一个对 象,那么在Cout对象当中存在一片用于数据存储的区域。ostream_iterator在STL中一般配合copy函数一起使用,如下代码;
1 2 3 4 5 6 7 8 9
| # demo 1 ostream_iterator output(cout, " "); copy(ivec.begin(), ivec.end(), output); cout;
# demo 2 copy(pre.begin(), pre.end(), ostream_iterator<ElemType>(cout)); cout << elements[i]; cout << endl;
|
REf:
C++监听文件夹下的添加、修改、删除文件事件_走过_冬天的博客-CSDN博客_c++ 监控文件删除
CSV
1、读csv文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| string fname = "test.csv";
ifstream csv_data(fname, ios::in);
if (!csv_data.is_open()) { cout << "Error: opening file fail" << endl; exit(1); } else { string line;
vector<string> words; string word; getline(csv_data, line);
istringstream sin; while (getline(csv_data, line)) { words.clear(); sin.clear();
sin.str(line); while (getline(sin, word, ',')) { cout << word << endl; words.push_back(word); } } csv_data.close(); }
|
2、写入csv文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| string fname = "test.csv";
ofstream outFile(fname, ios::out);
outFile << "name" << ',' << "income" << ',' << "expenditure" << ',' << "addr" << endl;
outFile << "zhangsan" << ',' << "3000" << ',' << "1200" << ',' << "陕西省" << endl;
outFile << "lisi" << ',' << to_string(2032.1) << ',' << to_string(789.2) << ',' << "北京市" << endl;
outFile.close();
|
3、向csv文件中追加内容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| ofstream outFile(fname, ios::app);
outFile << "wangwu" << ',' << "1234" << ',' << to_string(12.32) << ',' << "河南省" << endl;
outFile << "lisi" << ',' << to_string(2032.1) << ',' << to_string(789.2) << ',' << "北京市" << endl;
outFile.close();
|