fstat函数用于获取文件的属性信息(例如文件类型、访问权限和访问时间等)。函数原型如下:
#include <sys/stat.h>
int fstat(int filedes, struct stat *restrict buf);
其中 struct stat结构定义在文件 <sys/stat.h>中。(参考 4.2 stat函数)
返回值:成功返回0,出错返回-1。
参数:
1、filedes已打开的文件描述符。
2、buf存储struct stat结构信息的缓冲区。
fstat与stat只是第一个参数有差异,其他作用和用法都一样。
实例 x.4.2.2.c
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char pathname[] = "/tmp/myfile"; /*文件路径*/
int f_id; /*文件描述符*/
struct stat buf; /*属性信息*/
/*打开文件,获取文件描述符*/
if ((f_id = open(pathname, O_RDONLY | O_CREAT)) == -1) {
printf("open error for %s\n", pathname);
}
/*取文件属性信息*/
if (fstat(f_id, &buf) == -1) { /*调用stat将文件属性信息放入buf*/
printf("fstat error for %s\n",pathname);
exit(1);
} else {
printf("fstat OK for %s\n",pathname);
exit(0);
}
exit(0);
}
编译与执行:
[root@localhost unixc]# echo 'This is my tempfile!' > /tmp/myfile
[root@localhost unixc]# cc x.4.2.2.c
[root@localhost unixc]# ./a.out
fstat OK for /tmp/myfile
[root@localhost unixc]#