做網站建設要什么證小網站
注意文件的名字、路徑是如何輸入的。
函數(shù)opendir打開目錄,struct dirent,struct stat這些結構體的含義。?
????????readdir()函數(shù)是一個用于讀取目錄內容的系統(tǒng)調用或庫函數(shù),在類Unix操作系統(tǒng)中(如Linux)廣泛使用。它用于遍歷目錄,并逐個獲取目錄中的條目(文件和子目錄)。
????????lstat和stat是用于獲取文件信息的系統(tǒng)調用,主要在處理符號鏈接時存在差異。以下是它們之間的主要區(qū)別:
1. 處理符號鏈接:
? lstat:當使用lstat函數(shù)獲取一個符號鏈接的信息時,它返回的是符號鏈接本身的信息,而不是鏈接所指向文件的信息。這使得你能夠查看鏈接本身的屬性,而不用跟隨鏈接指向的文件。
? ?stat:當使用stat函數(shù)獲取一個符號鏈接的信息時,它會自動跟隨鏈接,返回鏈接指向的文件的信息,而不是鏈接本身的信息。
2. 跟隨鏈接:
? ?lstat:對于符號鏈接,lstat不會自動跟隨鏈接,它會返回鏈接本身的屬性,包括鏈接指向的路徑。
? stat:對于符號鏈接,stat會自動跟隨鏈接,返回鏈接指向的文件的屬性。
????????對于符號鏈接,`lstat`返回了鏈接本身的信息,而`stat`返回了鏈接指向的文件的信息。
/*===============================================
* 文件名稱:stat.c
* 創(chuàng) 建 者:WM
* 創(chuàng)建日期: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("-");}//鏈接數(shù)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;
}