繁体   English   中英

ostream :: write实际写入了多少字节?

[英]how many bytes actually written by ostream::write?

假设我向ostream :: write发送一个大缓冲区,但只有它的开头部分实际上已成功写入,其余部分未写入

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;
}

什么ostream函数可以告诉我实际写了多少字节?

您可以使用.tellp()来了解流中的输出位置,以计算写入的字节数:

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;
}

请注意,不能保证numberOfBytesWritten 确实是写入文件的字节数,但它应该适用于大多数情况,因为我们没有任何可靠的方法来获取写入文件的实际字节数。

我没有看到任何与gcount()相当的gcount() 直接写入streambuf(使用sputn() )会给你一个指示,但你的请求中存在一个基本问题:写入被缓冲,故障检测可以延迟到有效写入(刷新或关闭),没有办法访问操作系统真正写的内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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