使用stat函数,获取文件属性

Linux的终端下面,通过以下 ls 命令可获得文件属性,但是在程序中,需要获得文件属性,就需要使用 linux 的 stat/fstat/lstat 函数获得属性了。

我们先看看他们的函数原型:通过命令 “man 2 stat” 获得

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *path, struct stat *buf);
int fstat(int fd, struct stat *buf);
int lstat(const char *path, struct stat *buf);

这三个函数的区别是:

stat 用于获取有参数 file_name 指定的文件名的状态信息,保存在参数 struct stat *buf 中。fstat 于 stat 的区别在于 fstat 是通过文件描述符来指定文件,也就是 通过 open 函数所返回获得的 fd 。lstat 与 stat  的区别在于,对于符号链接文件,lstat 返回的是符号链接文件本身的状态信息,而 stat 返回的是符号链接指向的文件状态信息。

参数 struct stat *buf 是一个保存文件状态信息的结构体,其类型参考http://hi.baidu.com/546131278a/blog/item/4e059155d8d51e50d10906af.html

接下来只用调用这个函数来获得文件的属性,代码如下:

#include <stdio.h>
#include <time.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>

int main(int argc, char *argv[])
{
	struct stat buf;
	// 检查参数
	if (argc != 2) {
		printf("Usage: my_stat <filename>n");
		exit(0);
	}
	// 获取文件属性
	if ( stat(argv[1], &buf) == -1 ) {
		perror("stat:");
		exit(1);
	}
	// 打印出文件属性
	printf("device is: %dn", buf.st_dev);
	printf("inode is: %dn", buf.st_ino);
	printf("mode is: %on", buf.st_mode);
	printf("number of hard links  is: %dn", buf.st_nlink);
	printf("user ID of owner is: %dn", buf.st_uid);
	printf("group ID of owner is: %dn", buf.st_gid);
	printf("device type (if inode device) is: %dn", buf.st_rdev);
	printf("total size, in bytes is: %dn", buf.st_size);
	printf(" blocksize for filesystem I/O is: %dn", buf.st_blksize);
	printf("number of blocks allocated is: %dn", buf.st_blocks);
	printf("time of last access is: %s", ctime(&buf.st_atime));
	printf("time of last modification is: %s", ctime(&buf.st_mtime));
	printf("time of last change is: %s", ctime(&buf.st_ctime));
	return 0;
}

 

程序其实很简单,先检查参数个数是否为2,如果不是则退出。然后根据输入的文件名调用 stat 函数获取文件信息,然后存于结构体 buf 中。

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>