對於 文件的 讀寫, 當然是 文本文件 最好讀,最好寫,沒有 什麼文件結構 需要考慮。
對於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;
- }