获取文件属性

文件操作 / 基本操作

#include <string>
#include <fstream>
#include <sys/stat.h>
using namespace std;

string filePath = "C:\\tmp\\file.txt";

struct stat t_stat;
stat(filePath.c_str(), &t_stat);

//文件大小(第一种方法)
int fileSize1 = t_stat.st_size;

//文件大小(第二种方法)
ifstream in(filePath,
    ifstream::ate | ifstream::binary);
int fileSize2 = in.tellg();

//文件修改时间
time_t timeChanges = t_stat.st_mtime;

//最后一次状态变更的时间(所有者、权限);
//POSIX stat 没有文件创建时间
time_t statusChangeTime = t_stat.st_ctime;

// 文件是否可读
ifstream infile(filePath);
bool isReadable = infile.good();

int pos = filePath.find_last_of(".");
//文件扩展名
string extension = "";
if (pos > 0) {
    extension = filePath.substr(pos + 1);
}

pos = filePath.find_last_of("\\/");
//文件所在目录
string fileDir = "";
if (pos > 0) {
    fileDir = filePath.substr(0, pos);
}