vvv
vvv

Reputation: 21

Stop if reading a file takes more than 5 minutes (C++ std::ifstream)

I don't have my own code because I don't even know how to start, sorry. I can't find anything about std::ifstream file read and how to implement a timer.

I want to read a list of movies and if reading this file takes more than 5 minutes I want it to stop and std::cout that it takes too long. How to implement a timer in std::fstream?

Upvotes: 1

Views: 395

Answers (2)

Acorn
Acorn

Reputation: 26066

Consider solving the problem without timers.

Start by recording the current time. Then read the file chunk by chunk (i.e. not in a single call, but with a loop that reads a part of it). For every chunk, process it and then check the elapsed time with respect to the start. If it is bigger than your threshold, bail out.

In pseudocode:

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

    process(chunk);

    t = time();
    if (t - t0 > timeout)
        error();
}

Upvotes: 0

NuPagadi
NuPagadi

Reputation: 1440

You can use std::async. It returns a future object, on which you can wait_for specified maximum time interval.

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::launch::async means a new thread will be used.

Upvotes: 1

Related Questions