[英]How does a program determine the size of a file without reading it whole?
In the question Using C++ filestreams (fstream), how can you determine the size of a file? 在使用C ++文件流(fstream)的问题中,如何确定文件的大小? , the top answer is the following C++ snippet: ,最佳答案是以下C ++代码段:
ifstream file("example.txt", ios::binary | ios::ate);
return file.tellg();
Running it myself I noticed that the size of arbitrarily large files could be determined instantaneously and with a single read operation. 自己运行它我注意到任意大文件的大小可以瞬间确定并且只需一次读取操作。
Conventionally I would assume that to determine the size of a file, one would have to move through it byte-by-byte, adding to a byte-counter. 传统上我会假设要确定文件的大小,必须逐字节地移动它,添加到字节计数器。 How is this achieved instead? 这是如何实现的呢? Metadata? 元数据?
The size of the file is embedded in the file metadata in the file system. 文件的大小嵌入在文件系统的文件元数据中。 Different file systems have different ways of storing this information. 不同的文件系统具有不同的存储该信息的方式。
Edit Obviously, this is an incomplete answer. 编辑显然,这是一个不完整的答案。 When someone will provide an answer where he'll exemplify on a common filesystem like ex3 or ntfs or fat exactly how the file size it's known and stored, i'll delete this answer. 当有人提供一个答案,他将在ex3或ntfs这样的公共文件系统上进行例证,或者确切地知道它的文件大小是如何知道和存储的,我将删除这个答案。
The file size is stored as metadata on most filesystems. 文件大小作为元数据存储在大多数文件系统上。 In addition to GI Joe's answer above, you can use the stat function on posix systems: 除了上面的GI Joe的答案,你可以在posix系统上使用stat函数:
struct stat statbuf;
stat("filename.txt", &statbuf);
printf("The file is %d bytes long\n", statbuf.st_size);
When ios::ate
is set, the initial position will be the end of the file, but you are free to seek thereafter. 设置ios::ate
,初始位置将是文件的结尾,但此后您可以自由查找。
tellg
returns the position of the current character in the input stream. tellg
返回输入流中当前字符的位置。 The other key part is ios::binary
. 另一个关键部分是ios::binary
。
So all it does it seek to the end of the file for you when it opens the filestream and tell you the current position (which is the end of the file). 所以当它打开文件流并告诉你当前位置(这是文件的结尾)时,它会为你找到文件的末尾。 I guess you could say it's a sort of hack in a way, but the logic makes sense. 我想你可以说它在某种程度上是一种破解,但逻辑是有道理的。
If you would like to learn how filestreams work at a lower level, please read this StackOverflow question . 如果您想了解文件流如何在较低级别工作,请阅读此StackOverflow问题 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.