#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *pathname, struct stat *statbuf);
作用:获取一个文件相关的一些信息
参数:
- pathname:操作的文件的路径
- statbuf:结构体变量,传出参数,用于保存获取到的文件的信息
返回值:
成功:返回0
失败:返回-1 设置errno
int lstat(const char *pathname, struct stat *statbuf);
作用:获取一个文件软链接相关的一些信息
ln -s a.txt b.txt //b.txt是a.txt的软链接,
用stat获取的是a.txt内容,用lstat获取的是b.txt内容
参数:
- pathname:操作的文件的路径
- statbuf:结构体变量,传出参数,用于保存获取到的文件的信息
返回值:
成功:返回0
失败:返回-1 设置errno
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
int main(){
struct stat statbuf;
int ret = stat("a.txt", &statbuf);
if(ret == -1){
perror("stat");
return -1;
}
printf("size: %ld\n",statbuf.st_size);
return 0;
}
模拟实现ls -l命令
//模拟实现ls -l指令
//-rw-rw-r-- 1 nowcoder nowcoder 13 3-р с 4 20:55 a.txt
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <string.h>
int main(int argc, char * argv[]){
if(argc < 2){
printf("%s filename\n", argv[0]);
return -1;
}
//通过stat函数获取用户传入文件的信息
struct stat st;
int ret = stat(argv[1],&st);
if(ret == -1){
perror("stat");
return -1;
}
//获取文件类型
char perm[11] = {0};
switch(st.st_mode & __S_IFMT){
case __S_IFLNK:
perm[0] = 'l';
break;
case __S_IFSOCK:
perm[0] = 's';
break;
case __S_IFREG:
perm[0] = '-';
break;
case __S_IFBLK:
perm[0] = 'b';
break;
case __S_IFCHR:
perm[0] = 'c';
break;
case __S_IFIFO:
perm[0] = 'p';
break;
case __S_IFDIR:
perm[0] = 'd';
break;
case __S_IFMT:
perm[0] = 'i';
break;
default:
perm[0] = '?';
break;
}
//判断文件的访问权限
//文件所有者
perm[1] = (st.st_mode & S_IRUSR) ? 'r' : '-';
perm[2] = (st.st_mode & S_IWUSR) ? 'w' : '-';
perm[3] = (st.st_mode & S_IXUSR) ? 'x' : '-';
//文件所在组
perm[4] = (st.st_mode & S_IRGRP) ? 'r' : '-';
perm[5] = (st.st_mode & S_IWGRP) ? 'w' : '-';
perm[6] = (st.st_mode & S_IXGRP) ? 'x' : '-';
//其他人
perm[7] = (st.st_mode & S_IROTH) ? 'r' : '-';
perm[8] = (st.st_mode & S_IWOTH) ? 'w' : '-';
perm[9] = (st.st_mode & S_IXOTH) ? 'x' : '-';
//硬链接数量
int linkNum = st.st_nlink;
//文件所有者
char * fileUser = getpwuid(st.st_uid)->pw_name;
//文件所在组
char * fileGrp = getgrgid(st.st_gid)->gr_name;
//文件大小
long int fileSize = st.st_size;
//获取修改时间
char * time = ctime(&st.st_mtime);
char mtime[512] = {0};
strncpy(mtime, time, strlen(time) - 1);
char buf[1024];
sprintf(buf, "%s %d %s %s %ld %s %s",perm,linkNum,fileUser,fileGrp,fileSize,mtime,argv[1]);
printf("%s\n",buf);
return 0;
}