gpt4 book ai didi

c++ - 为什么 C++ 标准以它的方式处理文件查找?

转载 作者:行者123 更新时间:2023-12-03 00:21:08 28 4
gpt4 key购买 nike

C++ 使用 streamoff type 表示(文件)流内的偏移量,并在 [stream.types] 中定义如下:

using streamoff = implementation-defined ;

The type streamoff is a synonym for one of the signed basic integral types of sufficient size to represent the maximum possible file size for the operating system. 287)

287) Typically long long.

这是有道理的,因为它允许在大文件中进行查找(而不是使用 long ,后者可能只有 32 位宽)。

[filebuf.virtuals] 定义 basic_filebuf在文件中查找的函数如下:

pos_type seekoff(off_type off, ios_base::seekdir way, ios_base::openmode which = ios_base::in | ios_base::out) override;

off_type相当于 streamoff ,请参阅[iostreams.limits.pos]。然而,该标准随后解释了该功能的效果。我对最后一句话感到恼火,这需要调用 fseek :

Effects: Let width denote a_codecvt.encoding(). If is_open() == false, or off != 0 && width
<= 0
, then the positioning operation fails. Otherwise, if way != basic_ios::cur or off != 0, and if the last operation was output, then update the output sequence and write any unshift sequence. Next, seek to the new position: if width > 0, call fseek(file, width * off, whence), otherwise call fseek(file, 0, whence).

fseek接受long范围。如果off_typestreamoff定义为long long (按照标准的建议),这可能会导致向下转换为 long调用fseek(file, width * off, whence)时(导致可能难以诊断错误)。这让人对引入 streamoff 的整体理由产生疑问。在第一个位置输入。

这是故意的还是标准中的缺陷?

最佳答案

我认为您从中得出的结论是,C++ 流和 fseek 之间存在不匹配,这将导致运行时错误,这是不正确的。情况似乎是:

  1. long 为 64 位的系统上,streamoff 定义为 long,并且 seekoff > 函数调用 fseek

  2. long 为 32 位但操作系统支持 64 位文件偏移量的系统上,streamoff 定义为 long long seekoff 调用一个名为 fseekofseeko64 的函数,该函数接受 64 位偏移量。

这是我的 Linux 系统上 seekoff 定义的片段:

#ifdef _GLIBCXX_USE_LFS
if (!fseeko64(_M_file, __off, __whence))
__ret = std::streampos(ftello64(_M_file));
#else
if (!fseek(_M_file, __off, __whence))
__ret = std::streampos(std::ftell(_M_file));
#endif

LFS代表Large File Support .

结论:虽然标准建议的 streamoff 定义表面上与 seekoff 调用 fseek 的要求相冲突,但库设计者明白,他们必须调用接受操作系统支持的全部偏移量的 fseek 变体。

关于c++ - 为什么 C++ 标准以它的方式处理文件查找?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59328923/

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