12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
ADADADADAD
编程知识 时间:2024-12-04 20:26:41
作者:文/会员上传
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
在C++中同时读取多个文件,可以使用多线程或者多进程来实现。以下是使用多线程的示例代码:#include <iostream>#include <fstream>#include <vector>#include <thread>void rea
以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。
在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
函数中创建了多个线程来同时读取多个文件。每个线程负责读取一个文件,最后等待所有线程执行完成。
需要注意的是,多线程读取文件时要注意文件的互斥访问,可以使用互斥锁或者其他同步机制来保证文件的读取不会发生冲突。
11-20
11-19
11-20
11-20
11-20
11-19
11-20
11-20
11-19
11-20
11-19
11-19
11-19
11-19
11-19
11-19