目录
一、使用 tellg()
#include <iostream>
#include <fstream>
std::ifstream::pos_type get_file_size(const std::string& filename)
{
std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);
return in.tellg();
}
int main(int argc, char *argv[])
{
long filesize = get_file_size(argv[1]);
std::cout << "type = " << typeid(filesize).name() << std::endl << "size = " << filesize << std::endl;
return 0;
}
运行结果:
$ g++ get-file-size.cpp -o get-file-size
$ ./get-file-size get-file-size
type = l
size = 85920
二、使用 pubseekoff()
#include <iostream>
#include <fstream>
auto get_file_size(const std::string& filename)
{
std::ifstream in(filename, std::ios::binary);
return in.rdbuf() -> pubseekoff(0, std::ios::end, std::ios::in);
}
int main(int argc, char *argv[])
{
long filesize = get_file_size(argv[1]);
std::cout << "type = " << typeid(filesize).name() << std::endl << "size = " << filesize << std::endl;
return 0;
}
运行结果:
$ g++ --std=c++14 get-file-size.cpp -o get-file-size
$ ./get-file-size ./get-file-size
type = l
size = 85304
三、使用 file_size()(C++2017)
#include <iostream>
#include <filesystem>
auto get_file_size(const std::string &filename)
{
std::filesystem::path p = std::filesystem::current_path() / filename;
return std::filesystem::file_size(p);
}
int main(int argc, char *argv[])
{
long filesize = get_file_size(argv[1]);
std::cout << "type = " << typeid(filesize).name() << std::endl << "size = " << filesize << std::endl;
return 0;
}
运行结果:
$ g++ --std=c++17 get-file-size.cpp -o get-file-size
$ ./get-file-size get-file-size
type = l
size = 67888