共计 2773 个字符,预计需要花费 7 分钟才能阅读完成。
我们知道 Linux 中有一个命令叫 stat,它可以看到文件的各种属性,下面是文件 package.xml 的属性:
# stat package.xml
File: "package.xml"
Size: 31782 Blocks: 64 IO Block: 4096 普通文件
Device: fd00h/64768d Inode: 2243435 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 1000/ UNKNOWN) Gid: ( 1000/ UNKNOWN)
Access: 2014-06-17 16:40:45.432619616 +0800
Modify: 2011-05-15 06:14:56.000000000 +0800
Change: 2014-06-17 16:40:45.433679323 +0800
stat 用来判断没有打开的文件, 而 fstat 用来判断打开的文件. 我们使用最多的属性是 st_mode. 通过着属性我们可以判断给定的文件是一个普通文件还是一个目录, 连接等等. 可以使用下面几个宏来判断.
S_ISLNK(st_mode): 是否是一个连接.
S_ISREG 是否是一个常规文件.
S_ISDIR 是否是一个目录
S_ISCHR 是否是一个字符设备.
S_ISBLK 是否是一个块设备
S_ISFIFO 是否是一个 FIFO 文件.
S_ISSOCK 是否是一个 SOCKET 文件.
下面我们来仔细看一下 struct stat 结构的内容:
//! 需要包含 de 头文件
#include <sys/types.h>
#include <sys/stat.h>
int stat(const char *filename, struct stat *buf); //! prototype, 原型
struct stat
{
dev_t st_dev; /* ID of device containing file - 文件所在设备的 ID*/
ino_t st_ino; /* inode number -inode 节点号 */
mode_t st_mode; /* protection - 保护模式?*/
nlink_t st_nlink; /* number of hard links - 链向此文件的连接数 (硬连接)*/
uid_t st_uid; /* user ID of owner -user id*/
gid_t st_gid; /* group ID of owner - group id*/
dev_t st_rdev; /* device ID (if special file) - 设备号,针对设备文件 */
off_t st_size; /* total size, in bytes - 文件大小,字节为单位 */
blksize_t st_blksize; /* blocksize for filesystem I/O - 系统块的大小 */
blkcnt_t st_blocks; /* number of 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 - */
};
我们来写一个具体的实例来验证一下:
#include <stdio.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
int main (int argc ,char *argv[])
{
struct stat buf;
int result;
if(argc < 2 )
{ printf("%s [filename]\n",argv[0]);
return -1;
}
result = stat (argv[1], &buf);
if (result != 0)
{ perror ("Failed ^_^");
}
else
{
//! 文件的大小,字节为单位
printf("size of the file in bytes: %u\n" , buf.st_size );
//! 文件创建的时间
printf("time of creation of the file: %s\n" , ctime (&buf.st_ctime) );
//! 最近一次修改的时间
printf("time of last modification of the file: %s\n" ,ctime (&buf.st_mtime) );
//! 最近一次访问的时间
printf("time of last access of the file: %s\n", ctime (&buf.st_atime) );
}
return 0;
}
编译运行结果如下:
# ./stat stat.c
size of the file in bytes: 754
time of creation of the file: Tue Oct 14 16:28:39 2014
time of last modification of the file: Tue Oct 14 16:28:39 2014
time of last access of the file: Tue Oct 14 16:28:41 2014
正文完
扫码赞助
