1

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;
Community
  • 1
  • 1
Droide
  • 1,807
  • 2
  • 17
  • 30
  • On some operating systems (notably Linux) *another* process could modify an opened file, so the question might not make any sense (in other words, the retrieved size would always be approximate). – Basile Starynkevitch Nov 03 '16 at 12:12
  • @BasileStarynkevitch ok, but I don't think it is that the problem that I find in the linked question above.. no? – Droide Nov 03 '16 at 13:02

2 Answers2

3

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
Danh
  • 5,916
  • 7
  • 30
  • 45
3

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:

omusil
  • 289
  • 2
  • 10