码迷,mamicode.com
首页 > 系统相关 > 详细

Linux获取文件信息

时间:2014-10-28 17:01:27      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   ar   使用   sp   文件   

项目中需要对文件进行处理并分析,首先需要根据要求找到该文件,比如最后修改的文件

代码实现:

 1 #include <unistd.h>
 2 #include <sys/stat.h>
 3 #include <time.h>
 4 
 5 #include <iostream>
 6 
 7 using namespace std;
 8 
 9 int main(int argc, char **argv)
10 {
11     struct stat STFile;
12     stat("main.cpp", &STFile);
13     
14     cout << ctime(&STFile.st_mtime) << endl;
15     cout << ctime(&STFile.st_atime) << endl;
16 
17     return 0;
18 }

使用到的函数有:

stat,定义在sys/stat.h头文件中,用于根据文件名获取文件的信息

ctime定义在time.h头文件中,用于将时间time_t类型的时间转换为char*类型的时间

结构体有:struct stat

stat函数执行后,正确则返回0,否则返回-1,错误代码保存在errno中,如果执行成功,则将指定文件的信息填充到第二个参数指向的结构体中。

struct stat的定义如下:

 1 struct stat
 2 {
 3         mode_t     st_mode;       //文件对应的模式,文件,目录等
 4         ino_t      st_ino;       //inode节点号
 5         dev_t      st_dev;        //设备号码
 6         dev_t      st_rdev;       //特殊设备号码
 7         nlink_t    st_nlink;      //文件的连接数
 8         uid_t      st_uid;        //文件所有者
 9         gid_t      st_gid;        //文件所有者对应的组
10         off_t      st_size;       //普通文件,对应的文件字节数
11         time_t     st_atime;      //文件最后被访问的时间
12         time_t     st_mtime;      //文件内容最后被修改的时间
13         time_t     st_ctime;      //文件状态改变时间
14         blksize_t st_blksize;    //文件内容对应的块大小
15         blkcnt_t   st_blocks;     //伟建内容对应的块数量
16 };

其中,我们使用到的成员变量为st_mtime。得到该该变量,即可根据变量的值来确定哪个文件时最后被修改的,从而得到最新的文件。

st_mtime是time_t类型,输出就是一串数字,如果想要直观的查看时间,可以用ctime函数对其进行转换后输出,转换前后输出对比:

1 转换前:1414482116
2 转换后:Tue Oct 28 15:43:46 2014

 

Linux获取文件信息

标签:style   blog   io   color   os   ar   使用   sp   文件   

原文地址:http://www.cnblogs.com/lit10050528/p/4057057.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!