C++写入CSV的操作读取、写入、追加以及文件删除
说明
在C++的实际开发中,输出CSV文件是非常常见的任务,特别是在需要将数据导出到表格或其他工具中进行分析时。CSV文件本质上是以逗号分隔的纯文本文件,因此可以使用标准的文件流(std::ofstream)来生成和写入CSV文件。
以下是常用的几种方法和技巧,帮助在C++开发中高效地输出CSV文件。需要注意:csv文件按照","进行分隔。因此每个内容中需避免出现","。
具体操作
1、读取csv文件
c++通过文件读入方式打开文件。即通过ifstream类进行打开文件。
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>using namespace std;void PrintCSVLine(vector<string> line_data) {//此语法仅在C++11中适用for (string str: line_data) {cout << str << " ";}cout << endl;
}//读入csv文件
int main() {string fname = "mytest.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)) {// 清空vector及字符串流,只存当前行的数据words.clear();sin.clear();sin.str(line);//将字符串流sin中的字符读到字符串数组words中,以逗号为分隔符while (getline(sin, word, ',')) {//cout << word << endl;words.push_back(word); //将每一格中的数据逐个push}//输出此行中的内容PrintCSVLine(words);}csv_data.close();}}
读取csv文件内容如下:
2、写入csv文件
c++通过文件写入方式打开文件进行写入。即通过ofstream类进行写入,并在打开文件中指明ios::out。
备注:默认通过iso::out方式进行写入,当文件不存在时会进行创建
#include <iostream>
#include <fstream>
#include <string>using namespace std;int main() {string fname = "mytest.csv";ofstream outFile(fname, ios::out);if (outFile.is_open()) // 检查文件是否打开成功{// 写入标题行outFile << "name" << ','<< "year" << ','<< "salary" << ','<< "address" << endl;// ********写入两行数据*********outFile << "zhangsan" << ','<< "1985" << ','<< "13000.5" << ','<< "四川省成都市" << endl;outFile << "wangwu" << ','<< to_string(1990) << ','<< to_string(19000.9) << ','<< "北京市" << endl;//数字需转为字符串进行写入,csv文件结束一行写入需要"\n"或者endl进行换行outFile.close();} else {cout << "文件无法打开!" << endl;}
}
如下图:写入数据到mytest.csv文件中
3、向csv文件中追加数据
给写入部分几乎相同,只不过是打开文件时选择ios::app方式进行。当文件不存在时会进行创建。
#include <iostream>
#include <fstream>
#include <string>using namespace std;int main() {string fname = "mytest.csv";//先判断文件是否存在ifstream file(fname);if (!file.is_open()) {cout << "File does not exist!" << endl;return 1;} else {cout << "文件已存在,开始追加数据..." << endl;file.close();//必须先关闭文件后才可写入ofstream outFile(fname, ios::app);// ********写入两行数据*********outFile << "xiaoma" << ','<< "1980" << ','<< "13000.5" << ','<< "四川省成都市" << endl;outFile << "huateng" << ','<< to_string(1990) << ','<< to_string(19000.9) << ','<< "北京市" << endl;//数字需转为字符串进行写入,csv文件结束一行写入需要"\n"或者endl进行换行outFile.close();cout << "追加数据已完成!!!" << endl;}return 0;
}
如下图:追加数据到mytest.csv文件中
4、删除csv文件
这里使用的是C++标准库版本,可以使用C标准库中的remove
函数。
#include <iostream>
#include <cstdio> // For remove function
#include <string>int main() {std::string filename = "mytest.csv";if (remove(filename.c_str()) == 0) {std::cout << "File deleted successfully." << std::endl;} else {perror("Error deleting file"); // perror prints the last error message to stderr}return 0;
}
总结
以上代码使用了C++操作csv文件的基本操作,如果小伙伴喜欢的话,希望给点赞收藏加关注哦!!!! 感谢大家的支持!!!如发现此文章存在不足、缺陷、BUG,请联系我。