简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM