全國綠色計算大賽 模擬賽第一階段 第2關:檔案檢視器
阿新 • • 發佈:2019-02-10
欺負我檔案操作練的少,這道題檔案操作非常簡單,我開始的時候圖省事用遞迴+遞迴引數寫了一發,雖然用了不少時間但是感覺so easy啊,但是一想人家這是函式功能補全,我就開始想這個“+--”和“--”前面的空格數量怎麼控制,改了一晚上,用一個靜態變數就搞定了,看我下面的程式碼,至於檔案操作,請參看部落格https://blog.csdn.net/u010154760/article/details/45065457受益匪淺,感謝博主讓我又學到不少東西。
void showDirStructure(char *folderPath) { static int flor = 0; //層數 for (int i = 0; i < flor*2; i++) cout << " "; //輸出前置空格 char buf[256]; //存放當前最高路徑的資料夾名 int len = 0; for (int i = strlen(folderPath)-1; folderPath[i] != '/'; i--) buf[len++] = folderPath[i]; //folderPath是完整的攀附路徑,在此初步提取資料夾名 buf[len] = '\0'; for (int i = 0; i < len/2; i++) { //初步提取出的名稱是倒置的在此將他糾正 char t = buf[i]; buf[i] = buf[len-1-i]; buf[len-1-i] = t; } cout << "+--" << buf << endl; //將資料夾名稱輸出 DIR *dir = opendir(folderPath); struct dirent *i = NULL; while ((i = readdir(dir)) != NULL) { //讀取資料夾裡的內容 if (!strcmp(i->d_name, ".") || !strcmp(i->d_name, "..")) continue; //讀取出的內容包含.或..將其跳過 strcpy(buf, folderPath); strcat(buf, "/"); strcat(buf, i->d_name); //這3步string操作將完整的路徑名稱存放置buf中 struct stat M; stat(buf, &M); if (S_ISDIR(M.st_mode)) //判斷檔案型別是否為資料夾 { flor += 1; showDirStructure(buf); flor -= 1; //這裡運用到了回溯的思想 } else { for (int i = 0; i < (flor+1)*2; i++) cout << " "; //若為檔案則多輸出兩個空格然後輸出檔名 cout << "--" << i->d_name << endl; } } closedir(dir); }