Frage

In the question Using C++ filestreams (fstream), how can you determine the size of a file?, the top answer is the following C++ snippet:

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?

War es hilfreich?

Lösung

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.

Andere Tipps

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:

stat(3) manpage

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.

tellg returns the position of the current character in the input stream. The other key part is 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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top