使用 fseek() 读取文件的最后 50 个字符
我试图通过这样做来读取文件中的最后 50 个字符:
FILE* fptIn;
char sLine[51];
if ((fptIn = fopen("input.txt", "rb")) == NULL) {
printf("Coudln't access input.txt.\n");
exit(0);
}
if (fseek(fptIn, 50, SEEK_END) != 0) {
perror("Failed");
fclose(fptIn);
exit(0);
}
fgets(sLine, 50, fptIn);
printf("%s", sLine);
这不会返回任何远程有意义的内容。为什么?
I'm trying to read the last 50 characters in a file by doing this:
FILE* fptIn;
char sLine[51];
if ((fptIn = fopen("input.txt", "rb")) == NULL) {
printf("Coudln't access input.txt.\n");
exit(0);
}
if (fseek(fptIn, 50, SEEK_END) != 0) {
perror("Failed");
fclose(fptIn);
exit(0);
}
fgets(sLine, 50, fptIn);
printf("%s", sLine);
This doesn't return anything that makes sense remotely. Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将 50 更改为 -50。另请注意,这仅适用于固定长度字符编码,例如 ASCII。对于 UTF-8 之类的东西来说,找到倒数第 50 个字符绝非易事。
Change 50 to -50. Also note that this will only work with fixed-length character encodings like ASCII. Finding the 50th character from the end is far from trivial with things like UTF-8.
尝试将偏移量设置为-50。
Try setting the offset to -50.
除了偏移量的符号之外,以下事情也可能会造成麻烦:
换行符使 fgets 停止读取,但它被认为是有效字符,因此它包含在复制到 str 的字符串中。
使用ferror 或feof 检查是否发生错误或是否到达文件结尾。
另请参阅
Besides the sign of the offset the following things could make trouble:
A newline character makes fgets stop reading, but it is considered a valid character and therefore it is included in the string copied to str.
Use either ferror or feof to check whether an error happened or the End-of-File was reached.
See also
将流指针设置在文件末尾,然后尝试将光标定位在其前面 50 个字节。请记住,对于二进制流:
此调用应该会失败。下一次调用
fgets
会调用 UB。尝试 -50 作为偏移量,如果调用成功,则尝试将其读入缓冲区Sets the stream pointer at the end of the file, and then tries to position the cursor 50 bytes ahead thereof. Remember, for binary streams:
This call should fail. The next call to
fgets
invokes UB. Try -50 as an offset and also iff the call succeeds try to read it into your buffer