Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 使用fseek()读取文件的最后50个字符_C_File_Fseek - Fatal编程技术网

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

C 使用fseek()读取文件的最后50个字符,c,file,fseek,C,File,Fseek,我试图通过以下操作读取文件中的最后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

我试图通过以下操作读取文件中的最后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);

这不会返回任何有意义的远程信息。为什么?

将50更改为-50。还要注意,这只适用于固定长度的字符编码,如ASCII。对于UTF-8这样的东西,从末尾查找第50个字符绝非易事。

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

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

换行符使FGET停止读取,但它被视为有效字符,因此它包含在复制到str的字符串中

使用ferror或feof检查是否发生错误或是否到达文件末尾

fseek(fptIn,50,SEEK_END)

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

3对于二进制流,新位置(从文件开头开始以字符为单位)是通过将偏移量添加到指定的位置来获得的 位置是文件的开头,如果设置了SEEK_,则为文件的当前值 如果搜索当前,则定位指示器;如果搜索结束,则定位文件结束二进制流不需要 有意义地支持具有SEEK\u END whence值的fseek调用。

这个呼叫应该失败。对
fgets
的下一次调用调用UB。尝试-50作为偏移量,如果调用成功,尝试将其读入缓冲区

注:我的重点