mr******@gmail.com wrote:
Hello,
At my work we are implementing a progress bar status display which
increments a percentage bar by the number of bytes read of a file and
then comparing that to the full filesisze.
We are using the getline function in fstream and I have seen examples
that obtain the number of bytes reading a character at a time, but not
a line at a time.
I'm needing to be able to determine the number of bytes read in by
getline and then compare a sum of those values to the size of the
complete file. If anyone could help it would be greatly appreciated.
Here's an example that demonstrates some possibilities.
// mross.cpp - one way to get total file size, then
// read the file one 'line' at a time, keeping
// track of the number of bytes read.
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char * argv[])
{
if (argc < 2)
{
std::cout << "usage: mross file_to_read"
<< std::endl;
return 1;
}
std::fstream::pos_type len = 0;
std::fstream::pos_type tot = 0;
std::fstream f;
f.open(argv[1], std::ios_base::in |
std::ios_base::out |
std::ios_base::binary);
if (f)
{
// seek to the end of the file
f.seekg(0, std::ios_base::end);
if (f)
{
// get curr position (i.e. the file length)
len = f.tellg();
// seek back to the beginning of the file
f.seekg(0, std::ios_base::beg);
}
}
else
{
std::cerr << "failed to open " << argv[1]
<< std::endl;
return 2;
}
if (f.fail())
{
std::cerr << "seek/tell failed" << std::endl;
return 3;
}
std::cout << "size of file " << argv[1] << " is "
<< len << std::endl;
while (f)
{
std::string buf;
// read a line (up to the next newline) into 'buf'.
// the newline is discarded (not placed into buf)
// Note: use 'f.read()' rather than 'getline()' for
// truly binary files (jpegs, word docs, etc).
getline(f, buf);
if (f)
{
// add one for the newline read, but not saved,
// plus the length of the line read to 'tot'
tot += (1 + buf.length());
std::cout << "tot read: " << tot << std::endl;
}
}
f.close();
return 0;
}