copendir
函數本身并不用于刪除目錄,而是用于打開一個目錄流,以便讀取目錄中的條目。要刪除目錄,您可以使用 rmdir
或 rm -r
(在 Unix/Linux 系統上)命令。
以下是使用 C 語言和 opendir
、readdir
和 closedir
函數刪除目錄的示例:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
int remove_directory(const char *path) {
struct dirent *entry;
DIR *dp = opendir(path);
if (dp == NULL) {
perror("opendir");
return -1;
}
while ((entry = readdir(dp)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
if (remove(full_path) != 0) {
perror("remove");
closedir(dp);
return -1;
}
}
closedir(dp);
if (rmdir(path) != 0) {
perror("rmdir");
return -1;
}
return 0;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return 1;
}
if (remove_directory(argv[1]) == 0) {
printf("Directory removed successfully.\n");
} else {
printf("Failed to remove directory.\n");
}
return 0;
}
這個程序接受一個目錄路徑作為參數,并嘗試刪除該目錄及其所有內容。請注意,這個程序不會刪除非空目錄,除非您使用 rm -r
命令。