编辑,抱歉,这个问题显然与 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 上尝试了 Apple LLVM 4.2 (clang-425.0.28) for clang++ 和 i686-apple-darwin11-llvm-g++-4.2 for g++ and g++ (Debian 4.7.2-5) )
例如
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()
并没有错(然后可能写入文件)
您确实是在通过向前移动光标来写入此文件。
文件真的是否有那么大(如果它是 sparse file )完全取决于您的操作系统/文件系统:就 C++ 而言,这是有效的。
关于c++ - 这种关于 seekp 的看似奇怪的行为是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25281812/