Home > Article > Backend Development > How Can I Determine File Size in C With Minimal Dependencies?
Determining File Size in C with Minimal Dependencies
Retrieving file size is a common requirement in various programming scenarios. In C , numerous methods can be employed to achieve this. This article discusses a portable and reliable approach that minimizes external library dependencies.
One of the most straightforward methods to determine file size is using the std::ifstream class. This approach does not require any additional libraries and is widely supported across platforms such as Unix, Mac, and Windows.
#include <fstream> std::ifstream::pos_type file_size(const char* filename) { std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary); return in.tellg(); }
In this code, the ate flag specifies that the file stream should begin at the end of the file. The binary flag ensures that the file is opened in binary mode, which is essential for accurately determining the file size on all platforms.
The tellg() function returns the current position of the file pointer, which corresponds to the file's size. However, note that this approach may not always be reliable, as the tellg() function can return incorrect values under certain circumstances. Therefore, alternative methods may be necessary in some cases.
The above is the detailed content of How Can I Determine File Size in C With Minimal Dependencies?. For more information, please follow other related articles on the PHP Chinese website!