C++: File Size

Bjarne-stroustrup
 

C++ file size can be queried through filesystem metadata or inferred from suitable stream positions. The preserved helper seeks to the end of an input stream and subtracts its initial position. That small expression leaves important questions about opening, seeking and what unit the result represents.

C++ file size: reading the example

tellg can report failure rather than a usable position. The original does not check whether the file opened or whether seeking succeeded, so a returned difference is not automatically a valid size. A stream’s logical positions also need not behave like a count of raw bytes in every text-mode situation.

Check an empty regular file, a known binary file and a missing file in a dedicated test directory. A current filesystem::file_size query can make the regular-file intent clearer, with a deliberate exception or error-code policy. It still needs a valid path and failure handling.

Assumptions and limits of C++ file size

Directories and special streams are not ordinary seekable data files. A file can also change between a size check and a later read. The root-style demonstration paths are platform-dependent, and the original helper has not been advertised as a portable error-proof byte counter.

For the relevant definitions, consult the reference documentation. The explanation here does not claim that every preserved legacy fragment compiles unchanged.

Preserved original example

In this task, the job is to verify the size of a file called “input.txt” for a file in the current working directory and another one in the file system root.

#include <iostream>
#include <fstream>

std::ios::off_type getFileSize(const char *filename) {
	std::ifstream f(filename);
	std::ios::pos_type begin = f.tellg();
	f.seekg(0, std::ios::end);
	std::ios::pos_type end = f.tellg();
	return end - begin;
}

int main() {
	std::cout << getFileSize("input.txt") << std::endl;
	std::cout << getFileSize("/input.txt") << std::endl;
	return 0;
}

SOURCE

Content is available under GNU Free Documentation License 1.2.