C语言中获取文件状态的相关函数小结
C语言stat()函数:获取文件状态 #include <sys/stat.h> #include <unistd.h> 定义函数: int stat(const char * file_name,struct stat *buf); 函数说明:stat()用来将参数file_name 所指的文件状态,复制到参数buf 所指的结构中。 下面是struct stat 内各参数的说明: struct stat { dev_t st_dev; //device 文件的设备编号 ino_t st_ino; //inode 文件的i-node mode_t st_mode; //protection 文件的类型和存取的权限 nlink_t st_nlink; //number of hard links 连到该文件的硬连接数目,刚建立的文件值为1. uid_t st_uid; //user ID of owner 文件所有者的用户识别码 gid_t st_gid; //group ID of owner 文件所有者的组识别码 dev_t st_rdev; //device type 若此文件为装置设备文件,则为其设备编号 off_t st_size; //total size,in bytes 文件大小,以字节计算 unsigned long st_blksize; //blocksize for filesystem I/O 文件系统的I/O 缓冲区大小. unsigned long st_blocks; //number of blocks allocated 占用文件区块的个数,每一区块大小为512 个字节. time_t st_atime; //time of lastaccess 文件最近一次被存取或被执行的时间,一般只有在用mknod、utime、read、write 与tructate 时改变. time_t st_mtime; //time of last modification 文件最后一次被修改的时间,一般只有在用mknod、utime 和write 时才会改变 time_t st_ctime; //time of last change i-node 最近一次被更改的时间,此参数会在文件所有者、组、权限被更改时更新 }; 先前所描述的st_mode 则定义了下列数种情况: 返回值:执行成功则返回0,失败返回-1,错误代码存于errno。 错误代码: 范例 #include <sys/stat.h> #include <unistd.h> main() { struct stat buf; stat("/etc/passwd",&buf); printf("/etc/passwd file size = %d n",buf.st_size); } 执行: /etc/passwd file size = 705 C语言fstat()函数:由文件描述词取得文件状态 #include <sys/stat.h> #include <unistd.h> 定义函数: int fstat(int fildes,struct stat *buf); 函数说明:fstat()用来将参数fildes 所指的文件状态,复制到参数buf 所指的结构中(struct stat). Fstat()与stat()作用完全相同,不同处在于传入的参数为已打开的文件描述词. 详细内容请参考stat(). 返回值:执行成功则返回0,失败返回-1,错误代码存于errno. 范例 #include <sys/stat.h> #include <unistd.h> #include <fcntk.h> main() { struct stat buf; int fd; fd = open("/etc/passwd",O_RDONLY); fstat(fd,&buf); printf("/etc/passwd file size +%dn ",buf.st_size); } 执行: /etc/passwd file size = 705 C语言lstat()函数:由文件描述词取得文件状态 #include <sys/stat.h> #include <unistd.h> 定义函数: int lstat (const char * file_name,struct stat * buf); 函数说明:lstat()与stat()作用完全相同,都是取得参数file_name 所指的文件状态,其差别在于,当文件为符号连接时,lstat()会返回该link 本身的状态. 详细内容请参考stat(). 返回值:执行成功则返回0,错误代码存于errno. 范例:参考stat()。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |