温馨提示×

C++中怎么同时读取多个文件

c++
小亿
90
2024-04-15 18:16:12
栏目: 编程语言

在C++中同时读取多个文件,可以使用多线程或者多进程来实现。以下是使用多线程的示例代码:

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

void read_file(const std::string& filename) {
    std::ifstream file(filename);
    if (file.is_open()) {
        std::string line;
        while (std::getline(file, line)) {
            std::cout << line << std::endl;
        }
    } else {
        std::cerr << "Error opening file: " << filename << std::endl;
    }
}

int main() {
    std::vector<std::string> filenames = {"file1.txt", "file2.txt", "file3.txt"};

    std::vector<std::thread> threads;
    for (const auto& filename : filenames) {
        threads.push_back(std::thread(read_file, filename));
    }

    for (auto& thread : threads) {
        thread.join();
    }

    return 0;
}

在上面的代码中,我们定义了一个read_file函数用来读取单个文件的内容,然后在main函数中创建了多个线程来同时读取多个文件。每个线程负责读取一个文件,最后等待所有线程执行完成。

需要注意的是,多线程读取文件时要注意文件的互斥访问,可以使用互斥锁或者其他同步机制来保证文件的读取不会发生冲突。

0