【问题标题】:Is this seemingly odd behaviour concerning seekp correct?这种看似奇怪的关于 seekp 的行为是否正确?
【发布时间】:2014-08-13 20:39:14
【问题描述】:

编辑,抱歉,这个问题显然与failbit not being set when seekg seeks past end of file (C++,Linux)重复


要到达我所在的位置,首先在终端中触摸一个文件以创建一个空文件(linux 或 mac):

touch test.file

然后编译并执行这段代码

#include <fstream>
#include <iostream>

int main()
{
    std::fstream stream("test.file", std::ios::in | std::ios::out | std::ios::binary);
    stream.seekp(54765476543); // arbitrarily large number
    std::cout<<"stream.tellp() "<<stream.tellp()<<std::endl;
    std::cout<<"stream.bad()? "<<stream.bad()<<std::endl;
    std::cout<<"stream.fail()? "<<stream.fail()<<std::endl;
    stream << "test";
    stream.flush();
    stream.close();
    return 0;
}

使用您最喜欢的 c++ 编译器(我在 linux 上尝试了用于 clang++ 的 Apple LLVM 版本 4.2 (clang-425.0.28) 和用于 g++ 和 g++ (Debian 4.7.2-5) 的 i686-apple-darwin11-llvm-g++-4.2 )

例如

clang++ testStream.cpp -o ts

当我运行“ts”时,我得到了输出:

stream.tellp() 54765476543
stream.bad()? 0
stream.fail()? 0

这就是我产生困惑的地方:我认为 tellp() 会给出“-1”(因为我试图寻找结束)并且 stream.fail() 至少等于 true。这种行为是未定义的还是我遗漏了什么?

更奇怪的是当我这样做时

ls -lh test.file

我明白了

-rw-r--r--  1 bjones  users    51G Aug 13 04:32 test.file

现在很明显该文件的大小不是 54G。最后当我这样做时

cat test.file

要查看是否实际写入了任何内容,输出只是挂起。

上述行为是否正确?

谢谢,

本。

【问题讨论】:

  • 它是一个输出流,seekp 将从你的空 test.touch 中创建一个大小为 54765476543 的文件
  • 这不可能是真的,因为驱动器的“df”仅显示使用量增加了 8 个字节(我可以通过增加查找数来创建一个 10TB 的文件,至少根据 ls - h,远远超出驱动器的容量)
  • 您不会看到磁盘使用量大幅增加,因为它很可能是一个 sparse 文件,请参阅quantdev's answer
  • 啊,我不知道文件系统可以进行这样的优化。那讲得通。谢谢。

标签: c++ linux macos stream fstream


【解决方案1】:

在文件末尾执行seekp() 并没有错(然后可能写入它)

您确实是通过向前移动光标来编写此文件。

文件真的是否有那么大(如果是sparse file)完全取决于您的操作系统/文件系统:就C++而言,这是有效的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 2014-08-07
    • 2012-01-05
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 2018-07-24
    相关资源
    最近更新 更多