Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 701
Aviad Rozenhek Avatar asked Jan 09 '13 15:01

Aviad Rozenhek


People also ask

What does write mean C++?

The write() function shall attempt to write nbyte bytes from the buffer pointed to by buf to the file associated with the open file descriptor, fildes. Before any action described below is taken, and if nbyte is zero and the file is a regular file, the write() function may detect and return errors as described below.

Is Ostream an ofstream?

ofstream is an output file stream. It is a special kind of ostream that writes data out to a data file.

What is ofstream C++?

ofstream. This data type represents the output file stream and is used to create files and to write information to files. 2. ifstream. This data type represents the input file stream and is used to read information from files.


2 Answers

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.

like image 43
AProgrammer Avatar answered Oct 20 '22 23:10

AProgrammer


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.

like image 134
Nawaz Avatar answered Oct 21 '22 00:10

Nawaz