本文介绍了为什么POSIX允许在文件的现有末尾(fseek)之外搜索只读模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在文件末尾查找可能有用?为什么POSIX允许在打开的只读文件中查找示例?

Why seek over end of file can be usefull? Why POSIX let to seek like in example in file opened for read only?

c ++: http://en.cppreference.com/w/c/io /fseek posix: https://www.unix.com/man-page/posix /3P/fseek/

c++: http://en.cppreference.com/w/c/io/fseekposix: https://www.unix.com/man-page/posix/3P/fseek/

我在MinGW-64w上测试的下一个代码

Next code I test on 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;
}

推荐答案

总体上是否有用取决于实现.如您所知,尽管POSIX可以做到,但C和C ++并未指定必须成功执行此操作.但是,即使在非POSIX C中,

Whether it is useful or not in general depends on implementation. C and C++ do not specify that such an action must succeed, though POSIX does, as you seem to be aware. Even in non-POSIX C, however,

( C2011 7.21.9.2/2 )和

( C2011 7.21.9.2/5 ) .即使fseek使文件处于奇数(但有效)状态,也可能需要这些副作用.尽管如此,您的问题

(C2011 7.21.9.2/5). These side effects are potentially desirable even if the fseek leaves the file in an odd (but valid) state. That notwithstanding, your question

建议您认为fseek可能会失败,否则它会将(只读)文件放置在无法读取数据的位置.但是为什么要为此特例呢?可以将同时打开用于读取和写入的文件(根据POSIX)放置在其末端之后,然后读取该文件与读取放置类似位置的只读文件没有什么特别的区别.

suggests that you think perhaps fseek ought to fail if it otherwise would position the (read only) file at a point where no data can be read. But why make a special case for that? A file open for both reading and writing can (according to POSIX) be positioned past its end, and reading it then is not particularly different from reading a similarly-positioned read-only file.

使fseek在所有可搜索文件中保持一致的行为比您似乎欣赏的要有价值.

Making fseek's behavior consistent across all seekable files is of more worth than you seem to appreciate.

这篇关于为什么POSIX允许在文件的现有末尾(fseek)之外搜索只读模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 05:34