Linux高階程式設計基礎——檔案系統程式設計之遞迴遍歷/home目錄
阿新 • • 發佈:2018-11-10
檔案系統程式設計之遞迴遍歷/home目錄
/編寫程式完成以下功能:
1.遞迴遍歷/home目錄,打印出所有檔案和子目錄名稱及節點號。
2.判斷檔案型別,如果是子目錄,繼續進行遞迴遍歷,直到遍歷完所有子目錄為止。/
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <sys/stat.h> #include <sys/types.h> #include <dirent.h> int show (char * path) //該實驗使用的絕對路徑!!!!!!! { char p[500]; //定義一個數組 DIR *dir; //一個目錄流指標 struct stat statbuf; //檔案屬性結構體 struct dirent *dire; //目錄項 lstat (path,&statbuf); //讀取檔案“path”的屬性放在“statbuf"中 if (S_ISDIR(statbuf.st_mode)) //判斷檔案是否為目錄檔案 { dir = opendir (path); //開啟目錄檔案 if (dir) { while( (dire = readdir(dir) ) !=NULL) //讀目錄檔案 { if(( dire ->d_name[0] )=='.') //判斷是否為當前檔案,‘.’代表當前檔案 continue; //如果是結束此次迴圈 sprintf(p,"%s/%s",path,dire->d_name); //把path路徑(就是/home)和 “ / ” 和讀到的檔名都放在 p 陣列中,,這一步就是設定絕對路徑 lstat(p,&statbuf); //獲取檔案屬性 printf ("\t該目錄檔名為: %s \n",p); //輸出目錄檔名 printf ("\t該目錄檔案節點號為: %ld \n",statbuf.st_ino); //輸出目錄檔案節點號 show (p);//因為這是個目錄檔案,所以需要再次遍歷這個這個目錄,輸出這個目錄下的檔案的檔案資訊,所以在show函式裡面再次呼叫show函式 } //這一步就是遞迴 } } if (S_ISREG(statbuf.st_mode))//判斷檔案是否為常規檔案 { printf ("該檔名為: %s \n",path);//輸出檔名 printf ("該檔案節點號為: %ld \n",statbuf.st_ino);//輸出檔案節點號 } } int main() { show("/home"); //把絕對路徑作為引數傳遞給函式 return 0; }
/*
什麼是絕對路徑,什麼是相對路徑?
舉例解釋一下:
假如C盤ABC資料夾有個1檔案,還有一個DEF資料夾,而DEF檔案下有個2檔案.
那1和2的檔案路徑分別為:(都是絕對路徑)
C:\ABC\1
C:\ABC\DEF\2
如果讓1檔案來表示2檔案的路徑
絕對路徑: C:\ABC\DEF\2
相對路徑: DEF\2 (因為1和2檔案前面的C:\ABC這段路徑相同就不用寫出來了)。
*/