在Linux中,copendir()
函數用于打開一個目錄流,以便后續可以使用其他相關函數(如readdir()
、closedir()
等)來讀取目錄中的內容。以下是一些常見的使用場景:
最常見的是遍歷一個目錄下的所有文件和子目錄。
#include <dirent.h>
#include <stdio.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir("."); // 打開當前目錄
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return EXIT_SUCCESS;
}
可以在遍歷過程中檢查某個特定的文件或子目錄是否存在。
#include <dirent.h>
#include <stdio.h>
#include <string.h>
int main() {
DIR *dir;
struct dirent *entry;
const char *target = "example.txt";
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, target) == 0) {
printf("Found %s in the directory\n", target);
break;
}
}
closedir(dir);
return EXIT_SUCCESS;
}
可以獲取目錄中的所有條目,然后使用標準庫函數進行排序。
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compare(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
int main() {
DIR *dir;
struct dirent *entry;
char **files = NULL;
int count = 0;
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
while ((entry = readdir(dir)) != NULL) {
files = realloc(files, sizeof(char *) * (count + 1));
files[count] = strdup(entry->d_name);
count++;
}
closedir(dir);
qsort(files, count, sizeof(char *), compare);
for (int i = 0; i < count; i++) {
printf("%s\n", files[i]);
free(files[i]);
}
free(files);
return EXIT_SUCCESS;
}
可以在遍歷過程中統計目錄中的文件數量(不包括.
和..
)。
#include <dirent.h>
#include <stdio.h>
int main() {
DIR *dir;
struct dirent *entry;
int count = 0;
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
count++;
}
}
closedir(dir);
printf("Number of files: %d\n", count);
return EXIT_SUCCESS;
}
可以使用lstat()
函數來區分普通文件和符號鏈接,并進行相應的處理。
#include <dirent.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
int main() {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
while ((entry = readdir(dir)) != NULL) {
if (lstat(entry->d_name, &statbuf) == -1) {
perror("lstat");
continue;
}
if (S_ISREG(statbuf.st_mode)) {
printf("Regular file: %s\n", entry->d_name);
} else if (S_ISLNK(statbuf.st_mode)) {
printf("Symbolic link: %s\n", entry->d_name);
}
}
closedir(dir);
return EXIT_SUCCESS;
}
這些場景展示了copendir()
及其相關函數在目錄操作中的多種用途,從簡單的遍歷到復雜的文件系統分析和處理。