注意文件的名字、路徑是如何輸入的。
函數(shù)opendir打開(kāi)目錄,struct dirent,struct stat這些結(jié)構(gòu)體的含義。?
????????readdir()函數(shù)是一個(gè)用于讀取目錄內(nèi)容的系統(tǒng)調(diào)用或庫(kù)函數(shù),在類(lèi)Unix操作系統(tǒng)中(如Linux)廣泛使用。它用于遍歷目錄,并逐個(gè)獲取目錄中的條目(文件和子目錄)。
????????lstat和stat是用于獲取文件信息的系統(tǒng)調(diào)用,主要在處理符號(hào)鏈接時(shí)存在差異。以下是它們之間的主要區(qū)別:
1. 處理符號(hào)鏈接:
? lstat:當(dāng)使用lstat函數(shù)獲取一個(gè)符號(hào)鏈接的信息時(shí),它返回的是符號(hào)鏈接本身的信息,而不是鏈接所指向文件的信息。這使得你能夠查看鏈接本身的屬性,而不用跟隨鏈接指向的文件。
? ?stat:當(dāng)使用stat函數(shù)獲取一個(gè)符號(hào)鏈接的信息時(shí),它會(huì)自動(dòng)跟隨鏈接,返回鏈接指向的文件的信息,而不是鏈接本身的信息。
2. 跟隨鏈接:
? ?lstat:對(duì)于符號(hào)鏈接,lstat不會(huì)自動(dòng)跟隨鏈接,它會(huì)返回鏈接本身的屬性,包括鏈接指向的路徑。
? ?stat:對(duì)于符號(hào)鏈接,stat會(huì)自動(dòng)跟隨鏈接,返回鏈接指向的文件的屬性。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-683540.html
????????對(duì)于符號(hào)鏈接,`lstat`返回了鏈接本身的信息,而`stat`返回了鏈接指向的文件的信息。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-683540.html
/*===============================================
* 文件名稱(chēng):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)))//從第一個(gè)文件名開(kāi)始遍歷到最后。
{
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))//判斷文件類(lèi)型
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)//查看文件的權(quán)限
{
if(st.st_mode & 1<<i)
printf("r");
else
printf("-");
if(st.st_mode&1<<(i-1))
printf("w");
else
printf("-");
if(st.st_mode&1<<(i-2))
printf("x");
else
printf("-");
}
//鏈接數(shù)
printf(" %ld",st.st_nlink);
//用戶(hù)名
struct passwd *pw=getpwuid(st.st_uid);
printf(" %s ",pw->pw_name);
//用戶(hù)組名
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;
}
到了這里,關(guān)于IO進(jìn)程線(xiàn)程,文件與目錄,實(shí)現(xiàn)linux任意目錄下ls -la的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!