注意文件的名字、路径是如何输入的。
函数opendir打开目录,struct dirent,struct stat这些结构体的含义。
readdir()函数是一个用于读取目录内容的系统调用或库函数,在类Unix操作系统中(如Linux)广泛使用。它用于遍历目录,并逐个获取目录中的条目(文件和子目录)。
lstat和stat是用于获取文件信息的系统调用,主要在处理符号链接时存在差异。以下是它们之间的主要区别:
1. 处理符号链接:
lstat:当使用lstat函数获取一个符号链接的信息时,它返回的是符号链接本身的信息,而不是链接所指向文件的信息。这使得你能够查看链接本身的属性,而不用跟随链接指向的文件。
stat:当使用stat函数获取一个符号链接的信息时,它会自动跟随链接,返回链接指向的文件的信息,而不是链接本身的信息。
2. 跟随链接:
lstat:对于符号链接,lstat不会自动跟随链接,它会返回链接本身的属性,包括链接指向的路径。
stat:对于符号链接,stat会自动跟随链接,返回链接指向的文件的属性。
对于符号链接,`lstat`返回了链接本身的信息,而`stat`返回了链接指向的文件的信息。
/*===============================================
* 文件名称:stat.c
* 创 建 者:WM
* 创建日期:2023年08月24日
* 描 述:文件目录下除了隐藏文件查看
================================================*/
#include <stdio.h>
#include <sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<string.h>
#include<pwd.h>
#include<grp.h>
#include<time.h>
#include<dirent.h>
int main(int argc, char *argv[])
{ char path[100]={0};if(2!=argc){printf("error\n");return -1;}DIR * dirp=opendir(argv[1]);//获取所有的目录下的文件名struct dirent *a;//接收strcpy(path,argv[1]);while (NULL!=(a=readdir(dirp)))//从第一个文件名开始遍历到最后。{struct stat st;strcpy(path,argv[1]);strcat(path,"/");strcat(path,a->d_name);if(a->d_name[0]=='.')//去除隐藏文件continue;lstat(path,&st);//链接文件读取if(S_ISREG(st.st_mode))//判断文件类型printf("-");else if (S_ISDIR(st.st_mode))printf("d");else if(S_ISLNK(st.st_mode))printf("l");for ( int i=8; i >= 0; i-=3)//查看文件的权限{if(st.st_mode & 1<<i)printf("r");elseprintf("-");if(st.st_mode&1<<(i-1))printf("w");elseprintf("-");if(st.st_mode&1<<(i-2))printf("x");elseprintf("-");}//链接数printf(" %ld",st.st_nlink);//用户名struct passwd *pw=getpwuid(st.st_uid);printf(" %s ",pw->pw_name);//用户组名struct group *gr =getgrgid(st.st_gid);printf( "%s",gr->gr_name);//大小printf(" %ld",st.st_size);//去除换行char arr[100]={0};strcpy(arr,ctime(&st.st_mtime));if(arr[strlen(arr)-1]=='\n')arr[strlen(arr)-1]='\0';printf(" %s ",arr);printf(" %s ",a->d_name);puts("");}return 0;
}