int stat(const char* pathname, struct stat buf);
int fstat(int fd, struct stat* buf);
int lstat(const char* pathname, struct stat* buf);
若成功则为0,若出错则为-1
返回一个与pathname或fd指定的文件属性信息,存储在结构体buf中
(1)pathname:文件路径名
(2)buf:struct stat结构体
(1)lstat函数类似于stat,但是
当命名的文件是一个符号连接时,lstat返回该符号连接的有关信息
,
而不是由该符号连接引用的文件的信息
。
【编程实验】判断文件类型
//file_type.c
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
if(argc < 2){
fprintf(stderr, "usage: %s files\n", argv[0]);
exit(1);
struct stat buff;
int i = 0;
for(i=1; i<argc; i++){
memset(&buff, 0, sizeof(buff));
if(lstat(argv[i], &buff) < 0){ //使用lstat查看文件属性
perror("lstat error");
continue;
printf("%-20s", argv[i]); //左对齐输出文件名
//判断文件类型
if(S_ISREG(buff.st_mode))
printf("normal file");
}else if (S_ISDIR(buff.st_mode)){
printf("directory");
}else if (S_ISBLK(buff.st_mode)){
printf("block device");
}else if (S_ISCHR(buff.st_mode)){
printf("character device");
}else if (S_ISSOCK(buff.st_mode)){
printf("sock device");
}else if (S_ISFIFO(buff.st_mode)){
printf("name piped");
}else if (S_ISLNK(buff.st_mode)){
printf("link file");
}else{
printf("unknow type");
printf("\n");
return 0;