从文件中读取输入时创建进度条的最有效方法

Most efficient way of creating a progress bar while reading input from a file

本文关键字:方法 有效 创建 文件 读取 输入      更新时间:2023-10-16

我有一个程序,它从一个相当大的文件中读取输入,这个文件有数千行长。

话虽如此,我想在处理文件时实现一个进度条指示器。然而,我知道的大多数方法都需要使用getLine来计算文件中有多少行,以将其用作进度条的"预定义目标"(Boost示例(。这意味着我必须在一个大文本文件中循环两次,一次是计算行数,另一次是实际获取每一行并显示进度条。

有没有更有效的方法?

一个可能的解决方案是搜索到文件的末尾,只是为了了解输入的大小。然后,根据已处理文件的百分比不断更新进度条。这将为您提供一个非常漂亮和简单的进度条——它可以用ASCII艺术和回车(\r(进行修饰。

这里还有一个可能的实现:

# include <cmath>
# include <string>
# include <fstream>
# include <iomanip>
# include <iostream>

class reader : public std::ifstream {
public:
    // Constructor
    template <class... Args>
    inline reader(int max, Args&&... args) :
    std::ifstream(args...), _max(max), _last(0) {
        if (std::ifstream::is_open()) _measure();
    }
    // Opens the file and measures its length
    template <class... Args>
    inline auto open(Args&&... args)
    -> decltype(std::ifstream::open(args...)) {
        auto rvalue(std::ifstream::open(args...));
        if (std::ifstream::is_open()) _measure();
        return rvalue;
    }
    // Displays the progress bar (pos == -1 -> end of file)
    inline void drawbar(void) {
        int pos(std::ifstream::tellg());
        float prog(pos / float(_length)); // percentage of infile already read
        if (pos == -1) { _print(_max + 1, 1); return; }
        // Number of #'s as function of current progress "prog"
        int cur(std::ceil(prog * _max));
        if (_last != cur) _last = cur, _print(cur, prog);
    }
private:
    std::string _inpath;
    int _max, _length, _last;
    // Measures the length of the input file
    inline void _measure(void) {
        std::ifstream::seekg(0, end);
        _length = std::ifstream::tellg();
        std::ifstream::seekg(0, beg);
    }
    // Prints out the progress bar
    inline void _print(int cur, float prog) {
        std::cout << std::fixed << std::setprecision(2)
            << "r   [" << std::string(cur, '#')
            << std::string(_max + 1 - cur, ' ') << "] " << 100 * prog << "%";
        if (prog == 1) std::cout << std::endl;
        else std::cout.flush();
    }
};

int main(int argc, char *argv[]) {
    // Creating reader with display of length 100 (100 #'s)
    reader infile(std::atoi(argv[2]), argv[1]);
    std::cout << "-- reading file "" << argv[1] << """ << std::endl;
    std::string line;
    while (std::getline(infile, line)) infile.drawbar();
}

输出类似于:

$ ./reader foo.txt 50              # ./reader <inpath> <num_#'s>
-- reading file "foo.txt"
   [###################################################] 100.00%

请注意,参数是输入文件和进度条中所需的#数。我已经向std::ifstream::open函数添加了长度搜索,但drawbar()是由用户调用的。您可以将此函数插入std::ifstream的特定函数中。

如果你想让它更有趣,你还可以使用命令tput cols来了解当前shell中的列数。此外,您可以将这样的命令放入可执行文件中,使其比以下更清晰

$ ./reader foo.txt $(( $(tput cols) - 30 ))
-- reading file "foo.txt"
   [####################################################################] 100.00%

正如其他人所指出的,这种解决方案无法正确处理管道和临时文件,在这种情况下,您手头没有输入长度。非常感谢@NirMH的友好评论。