簡體   English   中英

如果讀取文件超過5分鍾,則停止(C ++ std :: ifstream)

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

我沒有自己的代碼,因為我什至不知道如何開始,對不起。 我找不到有關std::ifstream文件讀取以及如何實現計時器的任何信息。

我想閱讀電影列表,如果讀取該文件花費了5分鍾以上,我希望它停止並std::cout它花費的時間太長。 如何在std::fstream實現計時器?

您可以使用std::async 它返回一個future對象,您可以在上面wait_for指定的最大時間間隔。

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表示將使用新線程。

考慮在沒有計時器的情況下解決問題。

首先記錄當前時間。 然后逐塊讀取文件(即不是在單個調用中,而是通過循環讀取文件的一部分)。 對於每個塊,對其進行處理,然后檢查相對於開始的經過時間。 如果它大於閾值,請紓困。

用偽代碼:

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

    process(chunk);

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM