为什么查找文件末尾可以很有用?为什么POSIX允许在只读文件中进行示例中的查找?
c++: http://en.cppreference.com/w/c/io/fseek posix: https://www.unix.com/man-page/posix/3P/fseek/ 我在MinGW-64上测试了下面的代码。
c++: http://en.cppreference.com/w/c/io/fseek posix: https://www.unix.com/man-page/posix/3P/fseek/ 我在MinGW-64上测试了下面的代码。
#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;
}
fseek()
的更正确的 POSIX 链接应该是 http://pubs.opengroup.org/onlinepubs/9699919799/functions/fseek.html。 - Andrew Henleprintf("result = %zu,...
的输出中追加 post code,并且您的期望会增加问题的清晰度。(另外:有趣的代码没有使用std::printf
) - chux - Reinstate Monica