Return file size without read permission C ++

I use this piece of code

long filesize (const char * filename) { ifstream file (filename, ios::in|ios::binary); file.seekg (0, ios::end); return file.tellg(); } 

to return the file size in bytes. However, a file I without read permission results in a -1 return. Is there a way to use C ++ or c to return the size of a file and directories that works even in a file without read permission? I searched for a while, but did not find a solid solution.

+6
source share
3 answers

The current standard C ++ library does not allow you to request the file size from the file system.

In the future, when C ++ 17 is released, the C ++ standard library will have an API for basic file system operations . Using this API, this should not require permission to read the file (but you, of course, need permission to all the parent directories in the path), although I do not think that the standard provides any guarantees about non-compliance with permissions:

 return std::filesystem::file_size(filename); 

While the new standard is not supported by your standard library (some standard libraries already have experimental support, the technical specification of the experimental / file system ), you will need to refer to a specific API for the OS or a non-standard wrapper library .

+3
source

Well, without read permission, your file will remain in an error state, and calling file.seekg() will also result in an error:

 long filesize (const char * filename) { ifstream file (filename, ios::in|ios::binary); if(file) { // Check if opening file was successful file.seekg (0, ios::end); return file.tellg(); } return -1; // <<<< Indicate that an error occured } 

If the file does not allow you to open it, you can check the directory structure and get information about the files using stat() . But it depends on the platform (POSIX compliance) (and, of course, you need access rights to read information about the contents of directories).

+1
source

On a POSIX system, you can use stat .

Summary:

 #include <sys/stat.h> int stat(const char *restrict path, struct stat *restrict buf); 

So, you declare a stat structure to store the result and pass a pointer to stat:

 struct stat buf; stat(filename, &buf); 

The size (in bytes) is contained in buf.st_size .

If your standard library implementation includes <experimental/filesystem> (which should exit experimental with C ++ 17), you can use it instead. #include <experimental/filesystem> , and then use std::experimental::filesystem::file_size(filename) instead of your filesize function. (This also returns the size in bytes. It simply calls the stat function on POSIX systems.)

For GCC, you will need to set the -lstdc++fs link (see file system linker filter error ).

+1
source

All Articles