使用 fseek() 读取文件的最后 50 个字符

发布于 2024-08-21 12:34:08 字数 366 浏览 4 评论 0原文

我试图通过这样做来读取文件中的最后 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

黎夕旧梦 2024-08-28 12:34:08

将 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.

戏蝶舞 2024-08-28 12:34:08

尝试将偏移量设置为-50。

Try setting the offset to -50.

静若繁花 2024-08-28 12:34:08

除了偏移量的符号之外,以下事情也可能会造成麻烦:

换行符使 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

豆芽 2024-08-28 12:34:08

fseek(fptIn, 50, SEEK_END)

将流指针设置在文件末尾,然后尝试将光标定位在其前面 50 个字节。请记住,对于二进制流:

3 对于二进制流,新位置(从文件开头开始以字符为单位测量)是通过向whence..指定的位置添加偏移量来获得的
如果 SEEK_SET 是文件的当前值,则位置是文件的开头
如果是 SEEK_CUR,则为位置指示符;如果为 SEEK_END,则为文件结束符。 二进制流不需要
有意义地支持 wence 值为 SEEK_END 的 fseek 调用。

此调用应该会失败。下一次调用 fgets 会调用 UB。尝试 -50 作为偏移量,如果调用成功,则尝试将其读入缓冲区

注意:强调我的

fseek(fptIn, 50, SEEK_END)

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:

3 For a binary stream, the new position, measured in characters from the beginning of the file, is obtained by adding offset to the position specified by whence..The specified
position is the beginning of the file if whence is SEEK_SET, the current value of the file
position indicator if SEEK_CUR, or end-of-file if SEEK_END. A binary stream need not
meaningfully support fseek calls with a whence value of SEEK_END.

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

Note: emphasis mine

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文