简体   繁体   中英

How can I get the real size of a file with C++?

I'm using tellg() to get the size of some files, and it's very important for this project get the real/correct size of files. Now I'm bit worried because a read that tellg() doesn't work perfectly but it can get the wrong size, maybe bigger than the real size. For example here: tellg() function give wrong size of file?

How can I get the correct size?? or isn't it true that tellg does'nt work very well?

This is my code with tellg() :

streampos begin,end;
    ifstream file_if(cpd_file, ios::binary);
    begin = file_if.tellg();
    file_if.seekg(0, ios::end);
    end = file_if.tellg();
    file_if.close();
    size = end - begin;

At this moment, you can use boost::filesystem::file_size to get the file size.

In the near future, it will be standardized to std::filesystem::file_size , it's an experimental feature, see std::experimental::filesystem::file_size .

std::experimental::filesystem::file_size is supported by:

  • MSVC 2013 or later,
  • libstdc++ 5.3 or later
  • libc++ 3.8 or later

To get file's size and other info like it's creation and modification time, it's owner, permissions etc. you can use the stat() function.

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

struct stat s;
if (stat("path/to/file.txt", &s)) {
    // error
}

printf("filesize in bytes: %u\n", s.st_size);

Documentation:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM