#include
int stat(const char *pathname,struct stat *buf);--------------根据pathname返回与文件相关的信息
int fstat(int fields, struct stat *buf);-----------------------在文件描述符fields上打开文件的有关信息
int lstat(const char *pathname,struct stat *buf);-------------与state类似,但是当文件是一个符号链接时,lstat返回该符号链接的相关信息,而不是由该符号链接引用文件的信息。
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 */
};
1. st_mode
-
#include <sys/stat.h>
-
#include <sys/types.h>
-
#include <unistd.h>
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <errno.h>
-
#include <string.h>
-
-
int main(int argc, char* argv[])
-
{
-
int i;
-
struct stat buf;
-
char *ptr;
-
-
-
for(i = 1;i < argc; i++)
-
{
-
printf("%s: ",argv[i]);
-
if(sstat(argv[i],&buf) < 0) {
-
printf("lstat error:%s\n",strerror(errno));
-
continue;
-
}
-
if(S_ISREG(buf.st_mode)) {
-
ptr = "regular";
-
}else if(S_ISDIR(buf.st_mode)) {
-
ptr = "directory";
-
}else if(S_ISCHR(buf.st_mode)) {
-
ptr = "character special";
-
}else if(S_ISBLK(buf.st_mode)) {
-
ptr = "block special";
-
}else if(S_ISFIFO(buf.st_mode)){
-
ptr = "fifo";
-
}else if(S_ISLNK(buf.st_mode)) {
-
ptr = "symbolic link";
-
}else if(S_ISSOCK(buf.st_mode)){
-
ptr = "socket";
-
}else
-
ptr = "** unknow mode **";
-
printf("%s\n",ptr);
-
}
-
-
return 0;
-
}
gwwu@hz-dev2.wgw.com:~/test/file>gcc -g lstate.c -o lstate -Wall
gwwu@hz-dev2.wgw.com:~/test/file>./lstate /etc/passwd /etc/ /dev/log /dev/tty /dev/ram0 /dev/stderr
/etc/passwd: regular
/etc/: directory
/dev/log: socket
/dev/tty: character special
/dev/ram0: block special
/dev/stderr: symbolic link-----使用lstat时候显示是symblic link
当使用stat时候,/dev/stderr: character special, 因为实际指向类型是character special
2.
st_size
以字节为单位的文件长度。此字段只对普通文件,目录文件和符号链接文件有意义。
普通文件,文件长度可以为0;
目录文件,文件长度通常为某个数(16/512)的倍数;
符号链接文件,文件长度是文件名中的实际字节数:
lrwxrwxrwx. 1 root root 8 Oct 20 2012 tclsh -> tclsh8.5
8表示8个字节,就是tclsh8.5的长度。
3.st_blksize/st_blocks
st_blksize是对文件I/O比较合适的块长度,当将st_blksize用于读操作时,读一个文件所需的时间量最少。
st_blocks是所分配的实际512字节块的数量
阅读(683) | 评论(0) | 转发(0) |