一个可能的解决方案是寻找文件的末尾,只是为了了解输入的大小。然后,根据您已处理的文件的百分比不断更新进度条。这应该会给你一个非常漂亮和简单的进度条——它可以用 ASCII-art 和回车符 (\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%
请注意,参数是输入文件和进度条中所需的# 数。我已将 length-seek 添加到 std::ifstream::open 函数中,但 drawbar() 是由用户调用的。你可以在std::ifstream 的特定函数中插入这个函数。
如果你想让它更漂亮,你也可以使用命令tput cols 来了解当前 shell 中的列数。此外,您可以将这样的命令放在可执行文件中,以使其更清晰:
$ ./reader foo.txt $(( $(tput cols) - 30 ))
-- reading file "foo.txt"
[####################################################################] 100.00%
正如其他人指出的那样,此解决方案不适用于管道和临时文件,在这种情况下,您手头没有输入长度。非常感谢@NirMH,非常友好的评论。