Aviad Rozenhek
Aviad Rozenhek

Reputation: 2409

how many bytes actually written by ostream::write?

suppose I send a big buffer to ostream::write, but only the beginning part of it is actually successfully written, and the rest is not written

int main()
{
   std::vector<char> buf(64 * 1000 * 1000, 'a'); // 64 mbytes of data
   std::ofstream file("out.txt");
   file.write(&buf[0], buf.size()); // try to write 64 mbytes
   if(file.bad()) {
     // but suppose only 10 megabyte were available on disk
     // how many were actually written to file???
   }
   return 0;
}

what ostream function can tell me how many bytes were actually written?

Upvotes: 12

Views: 15625

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361612

You can use .tellp() to know the output position in the stream to compute the number of bytes written as:

size_t before = file.tellp(); //current pos

if(file.write(&buf[0], buf.size())) //enter the if-block if write fails.
{
  //compute the difference
  size_t numberOfBytesWritten = file.tellp() - before;
}

Note that there is no guarantee that numberOfBytesWritten is really the number of bytes written to the file, but it should work for most cases, since we don't have any reliable way to get the actual number of bytes written to the file.

Upvotes: 13

AProgrammer
AProgrammer

Reputation: 52314

I don't see any equivalent to gcount(). Writing directly to the streambuf (with sputn()) would give you an indication, but there is a fundamental problem in your request: write are buffered and failure detection can be delayed to the effective writing (flush or close) and there is no way to get access to what the OS really wrote.

Upvotes: 2

Related Questions