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

655Z技术栈 C/C++编程 2026年01月08日 9

在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函数中创建了多个线程来同时读取多个文件。每个线程负责读取一个文件,最后等待所有线程执行完成。

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

提供PHP及ThinkPHP框架的定制开发、代码优化,PHP修改、ThinkPHP修改。

邮箱:yvsm@163.com 微信:yvsm316 QQ:316430983
关闭

用微信“扫一扫”