在 CentOS 系統中,你可以使用 readdir
函數來讀取目錄中的文件和子目錄。但是,readdir
函數本身并不負責解壓縮文件。如果你想要在讀取目錄的同時解壓縮文件,你需要結合其他函數和工具來實現這個功能。
以下是一個簡單的示例,展示了如何在 CentOS 系統中使用 C 語言和 readdir
函數讀取目錄中的文件,并使用 system
函數調用 unzip
命令來解壓縮文件:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
char path[1024];
if (argc != 2) {
printf("Usage: %s <directory_path>\n", argv[0]);
return 1;
}
dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_REG) { // Check if it's a regular file
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
char command[2048];
snprintf(command, sizeof(command), "unzip -o %s -d /path/to/destination/%s", path, entry->d_name);
system(command);
}
}
closedir(dir);
return 0;
}
在這個示例中,我們首先使用 opendir
函數打開一個目錄,然后使用 readdir
函數讀取目錄中的每個條目。對于每個條目,我們檢查它是否是一個常規文件(而不是目錄或其他類型的文件)。如果是常規文件,我們構建一個 unzip
命令來解壓縮該文件,并使用 system
函數執行該命令。
請注意,這個示例僅用于演示目的,實際應用中可能需要更多的錯誤處理和功能。另外,直接使用 system
函數執行命令可能存在安全風險,因此在生產環境中建議使用更安全的方法(如 fork
和 exec
系列函數)來執行外部命令。