fstream.read 进度指示器

fstream.read progress indicator

本文关键字:指示器 read fstream      更新时间:2023-10-16

我尝试创建一个进度指示器来读取C++中的文件。我面临的问题是

  1. tellg()tellp() 在读取时都只返回 24 或 -1,即使文件的大小约为 400MB 编辑:从线程中读取文件 tellg() 返回正确的值
  2. 我不是在使用循环读取文件,而是使用单个read指令

代码(简体):

fstream file;
void readFile(string filename)
{
    file.open(filename, ios::in | ios::binary);
    file.read((char*) &buffer, buffersize);
}
void readFileWithProgressIndicator(string filename)
{
    size_t filesize = getFileSize(filename)
    thread file_read(readFile, filename);
    for( ; ; )
    {
        cout << file.tellg() << ":" << file.tellp() << endl;
    }
    file_read.join();
}

1-程序行为似乎是连贯的。看起来您刚刚通过 1 次调用读取了您的文件,我想您的缓冲区大小为 24。你能检查一下吗?

2-提案

std::atomic<std::streampos> fg;
std::atomic<std::streampos> fp;
void readFile(string filename)
{
    fstream file;
    file.open(filename, ios::in | ios::binary);
    file.read((char*) &buffer, buffersize);
    fg=file.tellg();
    fp=file.tellp();
}
void readFileWithProgressIndicator(string filename)
{
    size_t filesize = getFileSize(filename)
    thread file_read(readFile, filename);
    for( ; ; )
    {
        cout << fg << ":" << fp << endl;
    }
    file_read.join();
}