对于 文件的 读写, 当然是 文本文件 最好读,最好写,没有 什么文件结构 需要考虑。
对于windows 下的 excel 等文件 进行操作时就不是那么容易了,大家可以搜搜 ,基本上都是都复杂的方式才能读写
关键:
CSV 格式的文件,是一种文本文件,可以通过 C++ 的文件流简单的读写。 但是这种格式的文本文件,却是可以有 excel 默认支持的,所以用 excel 打开就是 excel文件。
代码如下;
- #include <fstream>
- #include <string>
- #include <iostream>
- #include <streambuf>
- using namespace std;
- int main()
- {
- //定义文件输出流
- ofstream oFile;
- //打开要输出的文件
- oFile.open("scoresheet.csv", ios::out | ios::trunc); // 这样就很容易的输出一个需要的excel 文件
- oFile << "姓名" << "," << "年龄" << "," << "班级" << "," << "班主任" << endl;
- oFile << "张三" << "," << "22" << "," << "1" << "," << "JIM" << endl;
- oFile << "李四" << "," << "23" << "," << "3" << "," << "TOM" << endl;
- oFile.close();
- //打开要输出的文件
- ifstream iFile("scoresheet.csv");
- string readStr((std::istreambuf_iterator<char>(iFile)), std::istreambuf_iterator<char>());
- cout << readStr.c_str();
- return 0;
- }