readdir 是一个用于读取目录内容的函数,通常与其它文件操作函数结合使用,以实现更复杂的文件处理任务。以下是一些常见的结合使用方式:
opendir 和 readdir首先,你需要使用 opendir 打开一个目录,然后使用 readdir 逐个读取目录中的条目。
#include <stdio.h>
#include <dirent.h>
#include <string.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;
}
stat 获取文件信息你可以使用 stat 函数获取每个目录条目的详细信息,例如文件类型、大小、修改时间等。
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
int main() {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
while ((entry = readdir(dir)) != NULL) {
char path[1024];
snprintf(path, sizeof(path), "./%s", entry->d_name);
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
if (S_ISREG(file_stat.st_mode)) {
printf("Regular file: %s\n", entry->d_name);
} else if (S_ISDIR(file_stat.st_mode)) {
printf("Directory: %s\n", entry->d_name);
}
}
closedir(dir);
return EXIT_SUCCESS;
}
fopen 和 fclose 读写文件你可以根据 readdir 获取的文件名,使用 fopen 打开文件并进行读写操作。
#include <stdio.h>
#include <dirent.h>
#include <string.h>
int main() {
DIR *dir;
struct dirent *entry;
FILE *file;
char path[1024];
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
while ((entry = readdir(dir)) != NULL) {
if (strstr(entry->d_name, ".txt")) {
snprintf(path, sizeof(path), "./%s", entry->d_name);
file = fopen(path, "r");
if (file == NULL) {
perror("fopen");
continue;
}
char buffer[1024];
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer);
}
fclose(file);
}
}
closedir(dir);
return EXIT_SUCCESS;
}
remove 删除文件你可以根据某些条件删除目录中的文件。
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
int main() {
DIR *dir;
struct dirent *entry;
char path[1024];
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
while ((entry = readdir(dir)) != NULL) {
if (strstr(entry->d_name, ".tmp")) {
snprintf(path, sizeof(path), "./%s", entry->d_name);
if (remove(path) == -1) {
perror("remove");
}
}
}
closedir(dir);
return EXIT_SUCCESS;
}
通过这些示例,你可以看到 readdir 如何与其他文件操作函数结合使用,以实现各种文件处理任务。根据具体需求,你可以灵活组合这些函数来完成更复杂的操作。