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:
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:
Linux version: stat(2)
Windows version: _stat, _stat32, _stat64, _stati64, _stat32i64, _stat64i32, _wstat, _wstat32, _wstat64, _wstati64, _wstat32i64, _wstat64i32
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.