C++写入CSV的利用、混合类型数据写入CSV、写入大数据

打印 上一主题 下一主题

主题 863|帖子 863|积分 2589

1、C++写文件利用

在C++的实际开辟中,输出CSV文件是非经常见的使命,特别是在必要将数据导出到表格或其他工具中进行分析时。CSV文件本质上是以逗号分隔的纯文本文件,因此可以使用标准的文件流(std:fstream)来生成和写入CSV文件。
以下是常用的几种方法和本领,帮助在C++开辟中高效地输出CSV文件。
1. 使用 std:fstream 直接写入 CSV 文件

std:fstream 是最常用的工具之一。可以使用它将数据写入文件,并以逗号分隔值。
示例代码:

  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include <vector>
  5. int main() {
  6.     // 打开 CSV 文件进行写入
  7.     std::ofstream csv_file("output.csv");
  8.     if (!csv_file.is_open()) {
  9.         std::cerr << "无法打开文件" << std::endl;
  10.         return 1;
  11.     }
  12.     // 写入 CSV 文件表头
  13.     csv_file << "Name, Age, Score" << std::endl;
  14.     // 一些示例数据
  15.     std::vector<std::tuple<std::string, int, double>> data = {
  16.         {"Alice", 30, 90.5},
  17.         {"Bob", 25, 85.0},
  18.         {"Charlie", 22, 78.2}
  19.     };
  20.     // 逐行写入数据
  21.     for (const auto& row : data) {
  22.         csv_file << std::get<0>(row) << ","
  23.                  << std::get<1>(row) << ","
  24.                  << std::get<2>(row) << std::endl;
  25.     }
  26.     // 关闭文件
  27.     csv_file.close();
  28.     std::cout << "CSV 文件已生成。" << std::endl;
  29.     return 0;
  30. }
复制代码
说明:



  • std:fstream 用于打开并写入文件。
  • 每行数据通过 , 分隔各个字段,末了使用 std::endl 进行换行。
  • 数据类型可以是任何类型,通常包罗字符串、整数和浮点数。

2. 处置惩罚特殊字符 (逗号、引号等)

在实际开辟中,CSV 文件中的数据有时会包含特殊字符,如逗号(,)、双引号(")或换行符(\n)。这些特殊字符必要进行得当的处置惩罚,通常的方法是:


  • 用双引号包裹含有逗号或换行符的字段
  • 将字段中的双引号转义为两个双引号
示例代码:

  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. // 用双引号包裹字段,并处理内部的双引号
  5. std::string escape_csv_field(const std::string& field) {
  6.     std::string result = field;
  7.     if (field.find(',') != std::string::npos || field.find('"') != std::string::npos || field.find('\n') != std::string::npos) {
  8.         result = """ + field + """;  // 用双引号包裹字段
  9.     }
  10.     return result;
  11. }
  12. int main() {
  13.     std::ofstream csv_file("output_with_special_chars.csv");
  14.     if (!csv_file.is_open()) {
  15.         std::cerr << "无法打开文件" << std::endl;
  16.         return 1;
  17.     }
  18.     // 写入包含逗号、引号等特殊字符的数据
  19.     std::string name = "Alice "the Great"";
  20.     std::string address = "123, Elm Street";
  21.     // 处理特殊字符并写入 CSV
  22.     csv_file << escape_csv_field(name) << "," << escape_csv_field(address) << std::endl;
  23.     csv_file.close();
  24.     std::cout << "CSV 文件已生成。" << std::endl;
  25.     return 0;
  26. }
复制代码
说明:



  • escape_csv_field 函数用于处置惩罚含有逗号、双引号或换行符的字段。
  • 假如字段中含有逗号或引号,则使用双引号将整个字段包裹起来,并将内部的双引号转义为 ""。

3. 处置惩罚不同类型的数据

在导出CSV时,数据类型可能会包含整数、浮点数、字符串、自定义类型等。通过 std:stringstream 连合 std:fstream,可以机动控制输特别式。
示例:导出混合类型数据到 CSV

  1. #include <iostream>
  2. #include <fstream>
  3. #include <sstream>
  4. #include <vector>
  5. #include <iomanip>  // 用于设置精度
  6. struct Person {
  7.     std::string name;
  8.     int age;
  9.     double score;
  10.     // toStr函数用于格式化每个Person
  11.     std::string toStr() const {
  12.         std::ostringstream oss;
  13.         oss << name << "," << age << "," << std::fixed << std::setprecision(2) << score;
  14.         return oss.str();
  15.     }
  16. };
  17. int main() {
  18.     std::ofstream csv_file("mixed_data_output.csv");
  19.     if (!csv_file.is_open()) {
  20.         std::cerr << "无法打开文件" << std::endl;
  21.         return 1;
  22.     }
  23.     // 写入表头
  24.     csv_file << "Name,Age,Score" << std::endl;
  25.     // 定义数据
  26.     std::vector<Person> people = {
  27.         {"Alice", 30, 95.567},
  28.         {"Bob", 25, 85.123},
  29.         {"Charlie", 22, 78.456}
  30.     };
  31.     // 写入每一行数据
  32.     for (const auto& person : people) {
  33.         csv_file << person.toStr() << std::endl;
  34.     }
  35.     csv_file.close();
  36.     std::cout << "CSV 文件已生成。" << std::endl;
  37.     return 0;
  38. }
复制代码
说明:



  • Person::toStr 函数用于格式化每个 Person 对象,将其转换为逗号分隔的字符串。
  • 通过 std:stringstream 来设置浮点数的精度(std::setprecision(2))确保输出的浮点数保留两位小数。

4. 逐行写入大数据

当处置惩罚大量数据(例如数百万行数据)时,逐行写入可能会更有效,而不是一次性将所有数据放入内存中再输出。std:fstream 支持逐行写入数据,这可以降低内存的占用。
示例:逐行写入大数据集

  1. #include <fstream>
  2. int main() {
  3.     std::ofstream csv_file("large_dataset_output.csv");
  4.     if (!csv_file.is_open()) {
  5.         std::cerr << "无法打开文件" << std::endl;
  6.         return 1;
  7.     }
  8.     // 写入表头
  9.     csv_file << "ID,Value" << std::endl;
  10.     // 假设有大量数据需要写入
  11.     for (int i = 1; i <= 1000000; ++i) {
  12.         csv_file << i << "," << i * 1.2345 << std::endl;
  13.     }
  14.     csv_file.close();
  15.     std::cout << "大数据集 CSV 文件已生成。" << std::endl;
  16.     return 0;
  17. }
复制代码
说明:



  • 该示例演示了逐行写入大数据集的方式。通过逐行写入淘汰了对内存的需求,适合处置惩罚大规模数据。

5. 使用第三方库处置惩罚 CSV

虽然 std:fstream 足以满意大多数 CSV 输出需求,但假如必要更高级的功能(如解析复杂的 CSV 文件、处置惩罚更多格式化需求),可以使用第三方库。
常用的第三方 CSV 库:


  • libcsv:一个简单的 C 库,支持高效地读写 CSV 数据。
  • CSV for C++:一个 C++ 的 CSV 解析和生成库,提供了更多的格式处置惩罚和容错功能。
  • rapidcsv:C++17 的轻量级 CSV 读写库,支持读写 CSV 文件并与 STL 容器连合使用。
这些库提供了更加高级的功能,比如对 CSV 格式的严格解析、自动处置惩罚转义字符等,适合对 CSV 文件有更多需求的场景。

总结

在 C++ 中处置惩罚 CSV 文件输出的常用方法包罗:

  • 使用 std:fstream 直接写入 CSV 文件,实用于大多数简单的 CSV 导出需求。
  • 处置惩罚特殊字符(如逗号、引号、换行符),确保输出的 CSV 符合规范。
  • 使用 std::ostringstream 处置惩罚复杂的格式化需求,特别是不同类型的数据格式化。
  • 逐行写入大数据集,以淘汰内存占用。
  • 对于更复杂的需求,可以考虑使用第三方库。
根据实际需求,可以选择不同的方法来处置惩罚 CSV 文件的输出。
2、写文件格式

在 C++ 中,文件写入的格式可以通过标准库的 std::ofstream 来实现。std::ofstream 是用于文件输出利用的类,支持多种数据格式的写入。可以控制文件的写入模式、格式化输出(如浮点数精度、分隔符等),并根据需求选择不同的写入格式。
文件写入的基本格式

使用 std::ofstream 写文件的基本步调如下:

  • 包含必要的头文件

    • #include <fstream>:用于文件输入输出。
    • #include <iostream>:用于标准输入输出(调试或打印错误信息)。
    • #include <sstream>:用于格式化输出时的字符串流利用。

  • 打开文件

    • 使用 std::ofstream 类创建文件输出流。
    • 可以指定文件的模式(覆盖模式、追加模式等)。

  • 写入数据

    • 使用流运算符(<<)将数据写入文件。
    • 控制数据格式,比如小数点位数、分隔符等。

  • 关闭文件

    • 通过 close() 关闭文件,确保数据被正确写入文件中。

示例:基本文件写入

  1. #include <iostream>
  2. #include <fstream>
  3. int main() {
  4.     // 创建一个 ofstream 对象,并打开文件
  5.     std::ofstream file("output.txt");
  6.     // 检查文件是否成功打开
  7.     if (!file.is_open()) {
  8.         std::cerr << "无法打开文件" << std::endl;
  9.         return 1;
  10.     }
  11.     // 向文件写入数据
  12.     file << "Hello, World!" << std::endl;
  13.     file << "Writing to a file in C++." << std::endl;
  14.     // 关闭文件
  15.     file.close();
  16.     std::cout << "数据已写入文件。" << std::endl;
  17.     return 0;
  18. }
复制代码
文件写入模式

std::ofstream 提供了几种常见的写入模式,控制文件的写入举动:

  • 默认模式(覆盖模式)

    • std::ofstream file("filename.txt"):默认模式,覆盖已存在的文件内容。

  • 追加模式(std::ios::app)

    • 在文件末端追加数据,而不是覆盖原有的内容。
    1. std::ofstream file("output.txt", std::ios::app);
    复制代码

  • 二进制模式(std::ios::binary)

    • 以二进制格式写入文件,实用于写入非文本数据(如图片、音频等)。
    1. std::ofstream file("output.bin", std::ios::binary);
    复制代码

  • 同时追加和二进制模式

    • 可以同时使用多个模式组合,如 std::ios::app | std::ios::binary。
    1. std::ofstream file("output.bin", std::ios::app | std::ios::binary);
    复制代码

控制输特别式

可以使用 C++ 的标准流库(如 std::ostringstream)或直接使用 std::ofstream 的格式控制功能,来指定文件中的数据格式。
1. 浮点数格式化

  1. #include <iostream>
  2. #include <fstream>
  3. #include <iomanip>  // 用于设置格式控制
  4. int main() {
  5.     std::ofstream file("formatted_output.txt");
  6.     if (!file.is_open()) {
  7.         std::cerr << "无法打开文件" << std::endl;
  8.         return 1;
  9.     }
  10.     // 设置浮点数格式为固定小数点,并保留2位小数
  11.     file << std::fixed << std::setprecision(2);
  12.     // 写入浮点数
  13.     file << "浮点数输出:" << 123.456789 << std::endl;
  14.     file.close();
  15.     return 0;
  16. }
复制代码
2. 控制字段宽度和填充

  1. #include <iostream>
  2. #include <fstream>
  3. #include <iomanip>  // 用于设置字段宽度和填充
  4. int main() {
  5.     std::ofstream file("formatted_output.txt");
  6.     if (!file.is_open()) {
  7.         std::cerr << "无法打开文件" << std::endl;
  8.         return 1;
  9.     }
  10.     // 设置字段宽度和填充字符
  11.     file << std::setw(10) << std::setfill('*') << "ID";
  12.     file << std::setw(10) << "Name" << std::setw(10) << "Score" << std::endl;
  13.     // 写入数据
  14.     file << std::setw(10) << 1 << std::setw(10) << "Alice" << std::setw(10) << 95.6 << std::endl;
  15.     file << std::setw(10) << 2 << std::setw(10) << "Bob" << std::setw(10) << 89.4 << std::endl;
  16.     file.close();
  17.     return 0;
  18. }
复制代码
说明


  • std::setw(10):设置字段宽度为10个字符。
  • std::setfill('*'):使用 * 填充空白位置。
3. 处置惩罚 CSV 格式输出

假如必要输出 CSV 格式的数据,可以使用逗号(,)作为分隔符。连合上面的格式控制,可以轻松生成 CSV 文件。
  1. #include <iostream>
  2. #include <fstream>
  3. int main() {
  4.     std::ofstream file("output.csv");
  5.     if (!file.is_open()) {
  6.         std::cerr << "无法打开文件" << std::endl;
  7.         return 1;
  8.     }
  9.     // 写入 CSV 表头
  10.     file << "Name,Age,Score" << std::endl;
  11.     // 写入数据
  12.     file << "Alice,30,95.6" << std::endl;
  13.     file << "Bob,25,89.4" << std::endl;
  14.     file.close();
  15.     return 0;
  16. }
复制代码
4. 二进制格式输出

对于非文本数据(如图片、音频等),可以使用二进制模式写入文件:
  1. #include <iostream>#include <fstream>int main() {    std::ofstream file("output.bin", std::ios::binary);
  2.     if (!file.is_open()) {        std::cerr << "无法打开文件" << std::endl;        return 1;    }    int numbers[5] = {1, 2, 3, 4, 5};    // 写入二进制数据    file.write(reinterpret_cast<char*>(numbers), sizeof(numbers));    file.close();    return 0;}
复制代码
说明


  • reinterpret_cast<char*>(numbers):将 int 数组转换为 char* 指针,便于以字节为单元写入。
  • sizeof(numbers):确定写入的数据巨细。
总结



  • std::ofstream 是 C++ 中用于文件输出的主要工具,可以机动控制输特别式。
  • 可以通过设置模式(如文本、二进制、追加等)控制文件写入方式。
  • 通过 iomanip 库,可以控制数据的输特别式,比如浮点数的精度、字段宽度、填充字符等。
  • 在输出 CSV 文件时,使用逗号作为分隔符,并留意对特殊字符(如引号、逗号)的处置惩罚。
  • 对于二进制文件,使用 write() 函数直接写入字节数据。
根据的具体需求,可以选择适合的格式控制方案来写入文件数据。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

用户国营

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表