日期:2014-05-16  浏览次数:20768 次

Linux/UNIX之文件和目录(1)

文件和目录(1)

stat、fstat和lstat函数

#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);

一旦给出path,stat函数返回与词文件相关的信息结构。fstat获取已在描述符fd上打开的有关信息。lstat类似于stat,但当命名的文件是一个符号连接时,lstat返回该符号链接的有关信息,而不是该符号链接引用文件的信息。

第二个参数buf是一个结构指针,该结构返回文件有关信息,其基本形式如下:

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 */

};

文件类型

文件类型包括以下几种:

普通文件、目录文件、块特殊文件、字符特殊文件、FIFO、套接字和符号链接。

文件类型信息包含在stat结构的st_mode成员中,可用下面的宏来确定文件类型:

S_ISREG():                  普通文件

S_ISDIR():                            目录文件

S_ISCHR():                 字符特殊文件

S_ISBLK():                   块特殊文件

S_ISFIFO():                 管道或FIFO

S_ISLINK():                 符号链接

S_ISSOCK():                套接字

如下程序取其命令参数,然后针对每一个命令参数打印其文件类型:

#include<unistd.h>

#include<stdio.h>

#include<sys/stat.h>

int main(int argc, char *argv[])

{

   &n