C++ 如果读取文件的时间超过5分钟,请停止(C+;+;std::ifstream)

C++ 如果读取文件的时间超过5分钟,请停止(C+;+;std::ifstream),c++,C++,我没有自己的代码,因为我甚至不知道如何开始,对不起。我找不到任何关于std::ifstream文件读取和如何实现计时器的信息 我想阅读电影列表,如果阅读此文件需要5分钟以上,我希望它停止并且std::cout时间太长。如何在std::fstream中实现计时器?您可以使用std::async。它返回一个对象,您可以在该对象上等待指定的最大时间间隔 std::ifstream file; auto f = std::async(std::launch::async, [&file]{ fi

我没有自己的代码,因为我甚至不知道如何开始,对不起。我找不到任何关于
std::ifstream
文件读取和如何实现计时器的信息


我想阅读电影列表,如果阅读此文件需要5分钟以上,我希望它停止并且
std::cout
时间太长。如何在
std::fstream
中实现计时器?

您可以使用
std::async
。它返回一个对象,您可以在该对象上等待指定的最大时间间隔

std::ifstream file;
auto f = std::async(std::launch::async, [&file]{ file.open("path/to/file"); });

auto status = future.wait_for(std::chrono::minutes(5));
if (status == std::future_status::timeout) {
    std::cout << "timeout\n";
    return 1;
} 
std::ifstream文件;
auto f=std::async(std::launch::async,[&file]{file.open(“path/to/file”);});
自动状态=未来。等待(std::chrono::minutes(5));
如果(状态==标准::未来状态::超时){

std::cout考虑在没有计时器的情况下解决问题

从记录当前时间开始。然后逐块读取文件(即,不是在单个调用中,而是通过读取其中一部分的循环)。对于每个块,处理它,然后检查相对于开始的经过时间。如果它大于阈值,则退出

在伪代码中:

t0 = time();
for (;;) {
    chunk = read();
    if (eof)
        success();

    process(chunk);

    t = time();
    if (t - t0 > timeout)
        error();
}
看起来非常类似:首先,对于这样一个“艰难”的时间,您可能只需要使用一个普通的c time()和difftime()函数。