gpt4 book ai didi

c - ftell 位于超过 2GB 的位置

转载 作者:行者123 更新时间:2023-11-30 16:35:46 26 4
gpt4 key购买 nike

在 32 位系统上,如果以二进制模式打开的文件的当前位置指示器超过 2GB 点,ftell 将返回什么?在C99标准中,这是未定义的行为,因为ftell必须返回一个long int(最大值为 >2**31-1)?

最佳答案

长整型

long int应该至少是 32 位,但 C99 标准并不将其限制为 32 位。C99 标准确实提供了便利类型,如 int16_t & int32_t等映射到目标平台的正确位大小。

在 ftell/fseek 上

ftell()fseek()在绝大多数 32 位体系结构系统上仅限于 32 位(包括符号位)。因此,当有大文件支持时,您会遇到 2GB 问题。

POSIX.1-2001 和 SysV 函数 fseekftellfseekoftello因为他们使用off_t作为偏移量的参数。

你确实需要用 -D_FILE_OFFSET_BITS=64 定义编译或者在包含 stdio.h 之前在某处定义它以确保 off_t是 64 位。

请访问 cert.org secure coding guide 了解此内容.

关于 ftell 和 long int 大小的混淆

C99 说 long int必须至少 32位,但并没有说不能更大

在 x86_64 架构上尝试以下操作:

#include <stdio.h>

int main(int argc, char *argv[]) {
FILE *fp;
fp = fopen( "test.out", "w");
if ( !fp )
return -1;
fseek(fp, (1L << 34), SEEK_SET);
fprintf(fp, "\nhello world\n");
fclose(fp);
return 0;
}

请注意 1L只是一个 long ,这将生成一个 17GB 的文件并粘贴 "\nhello world\n"到最后。您可以通过使用 tail -n1 test.out 来验证是否存在。或明确使用:

dd if=test.out skip=$((1 << 25))

请注意,dd 通常使用 block 大小 (1 << 9)所以34 - 9 = 25将转储 '\nhello world\n'

关于c - ftell 位于超过 2GB 的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48753886/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com