Data_Structure/作業/unit5/folder_info.cpp
2025-01-20 21:30:53 +08:00

99 lines
2.4 KiB
C++

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h> // 用於檢查是否為目錄
// 全域變數宣告
FILE *fp;
long fileCount = 0;
// 新增縮排輔助函式
void printIndent(int level) {
printf("|");
for(int i = 0; i < level; i++) {
printf(" "); // 每層縮排兩個空格
}
}
// 修改為遞迴版本
void open_folder(char *path, int level) {
DIR *dir;
struct dirent *entry;
char fullPath[512];
struct stat statbuf;
long fileSize;
// 開啟目錄
if ((dir = opendir(path)) == NULL) {
printf("無法開啟目錄: %s\n", path);
return;
}
// 讀取目錄內容
while ((entry = readdir(dir)) != NULL) {
// 跳過 . 和 ..
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
// 構建完整路徑
snprintf(fullPath, sizeof(fullPath), "%s/%s", path, entry->d_name);
// 取得檔案資訊
if (stat(fullPath, &statbuf) == -1) {
printf("無法取得檔案資訊: %s\n", fullPath);
continue;
}
// 印出目前層級的縮排
printIndent(level);
// 判斷是目錄還是檔案
if (S_ISDIR(statbuf.st_mode)) {
// 是目錄
printf("[資料夾] %s\n", entry->d_name);
// 遞迴處理子目錄
open_folder(fullPath, level + 1);
} else {
// 是檔案
if ((fp = fopen(fullPath, "rb")) != NULL) {
fseek(fp, 0, SEEK_END);
fileSize = ftell(fp);
fclose(fp);
printf(" %s (%ld bytes)\n", entry->d_name, fileSize);
fileCount++;
} else {
printf("%s (無法讀取)\n", entry->d_name);
}
}
}
closedir(dir);
}
int main() {
char directoryPath[128];
system("cls");
printf("\n輸入目錄夾路徑 ==> ");
scanf("%127[^\n]%*c", directoryPath);
// 移除路徑末尾的斜線(如果有的話)
size_t len = strlen(directoryPath);
if (len > 0 && (directoryPath[len-1] == '\\' || directoryPath[len-1] == '/')) {
directoryPath[len-1] = '\0';
}
if (opendir(directoryPath) == NULL) {
printf("目錄不存在!\n");
return -1;
}
printf("\n目錄內容結構如下:\n=======================================\n");
open_folder(directoryPath, 0);
printf("=======================================\n");
printf("總共有 %ld 個檔案\n", fileCount);
return 0;
}