#include<sys/types.h> #include<sys/stat.h> #include<unistd.h> intstat(const char*path,structstat *buf); intfstat(intfd,structstat *buf); intlstat(const char*path,structstat *buf); 这三个函数的区别是: stat用于获取有参数file_name指定的文件名的状态信息,保存在参数structstat *buf中。fstat于stat的区别在于fstat是通过文件描述符来指定文件,也就是通过open函数所返回获得的fd。lstat与stat 的区别在于,对于符号链接文件,lstat返回的是符号链接文件本身的状态信息,而stat返回的是符号链接指向的文件状态信息。 参数 structstat *buf是一个保存文件状态信息的结构体 文件对应的属性 接下来只用调用这个函数来获得文件的属性,代码如下: #include<stdio.h> #include<time.h> #include<sys/stat.h> #include<unistd.h> #include<sys/types.h> #include<errno.h> intmain(intargc,char*argv[]) { structstat 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: %d\n", buf.st_dev); printf("inode is: %d\n", buf.st_ino); printf("mode is: %o\n", buf.st_mode); printf("number of hard links is: %d\n", buf.st_nlink); printf("user ID of owner is: %d\n", buf.st_uid); printf("group ID of owner is: %d\n", buf.st_gid); printf("device type (if inode device) is: %d\n", buf.st_rdev); printf("total size, in bytes is: %d\n", buf.st_size); printf(" blocksize for filesystem I/O is: %d\n", buf.st_blksize); printf("number of blocks allocated is: %d\n", 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)); return0; } |
|