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,请联系我。

可以使用C++的fstream库来读取csv文件数据。具体步骤如下: 1. 包含头文件 ```cpp #include <fstream> #include <iostream> #include <string> #include <vector> ``` 2. 打开csv文件 ```cpp std::ifstream file("data.csv"); ``` 3. 读取csv文件数据 ```cpp std::vector<std::vector<std::string>> data; // 存储csv文件数据的二维向量 std::string line; // 存储每行数据的字符串 while (std::getline(file, line)) { // 逐行读取csv文件数据 std::vector<std::string> row; // 存储每行数据的一维向量 std::string cell; // 存储每个单元格的字符串 std::stringstream lineStream(line); // 将每行数据转换为字符串流 while (std::getline(lineStream, cell, ',')) { // 逐个单元格读取每行数据 row.push_back(cell); // 将单元格字符串添加到一维向量中 } data.push_back(row); // 将一维向量添加到二维向量中 } ``` 4. 关闭csv文件 ```cpp file.close(); ``` 完整代码如下: ```cpp #include <fstream> #include <iostream> #include <string> #include <vector> int main() { std::ifstream file("data.csv"); std::vector<std::vector<std::string>> data; std::string line; while (std::getline(file, line)) { std::vector<std::string> row; std::string cell; std::stringstream lineStream(line); while (std::getline(lineStream, cell, ',')) { row.push_back(cell); } data.push_back(row); } file.close(); // 输出读取csv文件数据 for (const auto& row : data) { for (const auto& cell : row) { std::cout << cell << " "; } std::cout << std::endl; } return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

angelasp

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值