Home > Backend Development > C++ > body text

How to Determine File Size in C Without External Libraries?

Mary-Kate Olsen
Release: 2024-11-12 21:20:02
Original
328 people have browsed it

How to Determine File Size in C   Without External Libraries?

Determining File Size in C

How can I obtain the size of a file in C while maintaining portability, reliability, and simplicity, without incurring library dependencies?

Solution:

The most common and reliable method to determine file size in C is by utilizing the std::ifstream class. Here's how you can implement it:

#include <fstream>

std::ifstream::pos_type filesize(const char* filename)
{
    std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);
    return in.tellg();
}
Copy after login

In this code:

  • std::ifstream(filename, std::ifstream::ate | std::ifstream::binary) opens the specified file for reading.
  • std::ifstream::ate positions the file pointer at the end of the file.
  • std::ifstream::binary ensures the file is read in binary mode.
  • in.tellg() retrieves the current position of the file pointer, which represents the file size.

Note:
It's important to note that this solution uses tellg(), which doesn't always return the correct file size on certain systems. Refer to this discussion for additional information: http://stackoverflow.com/a/22986486/1835769.

The above is the detailed content of How to Determine File Size in C Without External Libraries?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template