stat()函数--------------获取文件信息
stat():用于获取文件的状态信息,使用时需要包含<sys/stat.h>头文件。
函数原型:int stat(const char *path, struct stat *buf);
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for file system I/O */
blkcnt_t st_blocks; /* number of 512B blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last status change */
};
示例:
int main(int argc, char* argv[]) { struct stat buf; char* path = "E:\\1.txt"; int res = stat(path, &buf); if (res != 0) { perror("Problem getting information"); switch (errno) { case ENOENT: printf("File %s not found.\n", path); break; case EINVAL: printf("Invalid parameter to _stat.\n"); break; default: /* Should never be reached. */ printf("Unexpected error in _stat.\n"); } } //获取文件类型 if (buf.st_mode & S_IFREG) printf("regular file\n"); else if (buf.st_mode & S_IFDIR) printf("dir \n"); else printf("other\n"); //获取大小 printf("SIZE %d\n", buf.st_size); char timeBuf[26] = { 0 }; printf("%lld\n", buf.st_ctime); //文件最后访问时间 errno_t err = ctime_s(timeBuf, 26,&buf.st_atime); if (err) { printf("Invalid arguments to ctime_s."); return -1; } printf("Time visit %s\n", timeBuf); //文件最后修改时间 err = ctime_s(timeBuf, 26, &buf.st_mtime); if(err) { printf("Invalid arguments to ctime_s."); return -1; } printf("Time modified %s\n", timeBuf); system("pause"); return 0; }
示例及参考来源:https://docs.microsoft.com/zh-cn/cpp/c-runtime-library/reference/stat-functions