C++使用多线程将数据写入文件

#include <iostream>
#include <vector>
#include <thread>
#include <fstream>

// 使用多线程将数据写入文件
void writeToFile(const std::vector<std::string>& data, const std::string& filename) {
    // 创建一个文件输出流
    std::ofstream file(filename, std::ios::out | std::ios::binary);
    // 如果文件无法打开,输出错误信息并返回
    if (!file) {
        std::cerr << "File could not be opened!" << std::endl;
        return;
    }

    // 创建一个线程向量
    std::vector<std::thread> threads;
    // 对数据中的每个字符串,创建一个新线程并将其写入文件
    for (const auto& str : data) {
        threads.push_back(std::thread([&]() {
            file.write(str.c_str(), str.size());
            }));
    }

    // 等待所有线程完成
    for (auto& t : threads) {
        if (t.joinable()) {
            t.join();
        }
    }

    // 关闭文件
    file.close();
}

// 主函数
int main()
{
    // 创建一个字符串向量
    std::vector<std::string> data = { "Hello", "World" };
    // 定义文件名
    std::string filename = "output.txt";
    // 调用函数,将数据写入文件
    writeToFile(data, filename);
}

 

posted @ 2023-11-03 15:08  阿坦  阅读(914)  评论(0)    收藏  举报