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

标签 c++ buffer iostream

假设我向 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 确实是 写入文件的字节数,但它应该适用于大多数情况,因为我们没有获取写入文件的实际字节数的任何可靠方法。

关于c++ - ostream::write 实际写入了多少字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14238572/

相关文章:

c++ - 非静态和静态数据和函数

c++ - 使用 composing() 和 implicit_value() boost program_options 不是 "composed"

c++ - 在 Qt 中使用正则表达式查找两个标签之间的字符串

memory - Node.js 内存泄漏

c++ - 库 'stdio' 与 'iostream' 的速度和稳定性

c++ - C++ IO 流简介

c++ - 库达和库布拉斯 :call a global function after using cublas

java - 处理 Buffer 内多条消息的异常 [JAVA-Mina]

java - 三重缓冲区严重闪烁

java - 如何在 Java 中重新分区文件中的每一行