假设我向 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/