gpt4 book ai didi

c++ - seekg 是如何找到文件末尾的?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:24:11 25 4
gpt4 key购买 nike

在对文件使用 seekg 和 tellg 的场景中,我想知道幕后发生了什么?

    // Open file and get file size
int myFileSize;
std::fstream myFile;
myFile.open(myFileName, std::ios::in|std::ios::binary);
if (myFile.is_open())
{
myFile.seekg(0, std::ios::end);
myFileSize = myFile.tellg();
myFile.seekg(0, std::ios::beg);
myFile.close();
}

Q1: seekg 实际上是遍历整个文件的内容,直到它找到一些特殊的“EOF 字符”吗?或者它是否使用文件系统提供的一些其他信息来“知道”文件末尾在哪里?

Q2: seekg 是一个流搜索操作。这是否意味着文件的全部内容必须通过流?

如果我对这一切的工作原理只有初步的了解,请原谅我。

最佳答案

Q1:不会。操作系统会知道文件的大小,seekg() 会使用该信息——无论文件的长度是 1、100 还是 10000000000 字节,它花费的时间几乎相同。

Q2:不是。它只是设置当前的“get pointer”,在 Windows 或 Linux 系统中转换为“SetFilePos”或“lseek”。几乎所有其他操作系统都有类似的概念。

关于c++ - seekg 是如何找到文件末尾的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14793122/

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