为什么在文件末尾查找很有用?为什么 POSIX 允许像示例中那样在以只读方式打开的文件中查找?
C++:http://en.cppreference.com/w/c/io/fseek 正位:https://www.unix.com/man-page/posix/3P/fseek/
我在 MinGW-64w 上测试的下一个代码
#include <cassert>
#include <cstdio>
#include <cstring>
int main() {
std::FILE* f = std::fopen("tmp_file.txt", "wb");
auto result = std::fwrite("1", 1, 1, f);
assert(result == 1);
result = std::fclose(f);
assert(result == 0);
f = std::fopen("tmp_file.txt", "rb"); // READ ONLY binary mode
result = std::fseek(f, 100500, SEEK_SET);
assert(result == 0); // WHY I can seek to not existing position in file?
// opended in READ_ONLY mode?
char buff[100500] = {0};
result = std::fread(&buff, sizeof(buff), 1, f);
printf("result = %zu, errno: %s ferror(f): %d feof(f): %d", result,
std::strerror(errno), std::ferror(f), std::feof(f) != 0);
return result;
}
最佳答案
Why seek over end of file can be usefull?
它是否有用一般取决于实现。 C 和 C++ 没有指定这样的操作必须成功,尽管 POSIX 确实如此,正如您似乎知道的那样。然而,即使在非 POSIX C 中,
If a read or write error occurs [within
fseek
], the error indicator for the stream is set andfseek
fails
( C2011 7.21.9.2/2 ), 和
a successful call to the
fseek
function undoes any effects of theungetc
function on the stream, clears the end-of-file indicator for the stream
(C2011 7.21.9.2/5)。即使 fseek
使文件处于奇怪(但有效)状态,这些副作用也可能是需要的。尽管如此,你的问题
Why POSIX let to seek like in example in file opened for read only?
建议您认为 fseek
可能应该失败,否则会将(只读)文件定位在无法读取数据的位置。但为什么要为此特例呢?一个为读写而打开的文件可以(根据 POSIX)定位到它的末尾之后,然后读取它与读取一个类似定位的只读文件并没有特别不同。
使 fseek
的行为在所有可搜索文件中保持一致的值(value)超出您的想象。
关于c++ - 为什么 POSIX 允许在现有文件结尾 (fseek) 之外寻找只读模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48585111/