在Debian系統中,readdir
函數用于讀取目錄中的條目。當處理文件刪除操作時,通常需要結合其他函數來實現。以下是一個簡單的示例,展示了如何使用opendir
、readdir
和closedir
函數來遍歷目錄,并使用remove
函數刪除特定文件。
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return 1;
}
DIR *dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 跳過當前目錄和上級目錄的特殊條目
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 構建文件的完整路徑
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
// 獲取文件信息
struct stat statbuf;
if (stat(path, &statbuf) == -1) {
perror("stat");
closedir(dir);
return 1;
}
// 檢查是否為普通文件
if (S_ISREG(statbuf.st_mode)) {
// 刪除文件
if (remove(path) == -1) {
perror("remove");
} else {
printf("Deleted file: %s\n", path);
}
}
}
closedir(dir);
return 0;
}
opendir
函數打開指定目錄。readdir
函數讀取目錄中的每個條目。.
和..
這兩個特殊條目。snprintf
函數構建文件的完整路徑。stat
函數獲取文件的信息,以確定它是否為普通文件。remove
函數刪除它。這個示例展示了如何在Debian系統中使用C語言處理目錄遍歷和文件刪除操作。你可以根據需要進一步擴展和修改這個示例。