readdir
是POSIX标准库函数,用于读取目录内容,在CentOS等Linux系统中广泛使用。以下是几种常见使用场景的脚本编写方法。
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
exit(EXIT_FAILURE);
}
DIR *dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
编译运行:gcc -o readdir_test readdir_test.c
,然后执行./readdir_test /path/to/directory
。
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
void traverse(const char *path) {
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return;
}
struct dirent *entry;
char full_path[1024];
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
struct stat statbuf;
if (stat(full_path, &statbuf) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(statbuf.st_mode)) {
printf("Directory: %s\n", full_path);
traverse(full_path);
} else {
printf("File: %s\n", full_path);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
exit(EXIT_FAILURE);
}
traverse(argv[1]);
return 0;
}
编译运行:gcc -o recursive_readdir recursive_readdir.c
,然后执行./recursive_readdir /path/to/directory
。
#!/bin/bash
traverse_dir() {
local dir=$1
for item in "$dir"*/; do
if [ -d "$item" ]; then
echo "Directory: $item"
traverse_dir "$item"
else
echo "File: $item"
fi
done
}
traverse_dir "."
使用方法:将脚本保存为traverse.sh
,添加执行权限chmod +x traverse.sh
,然后执行./traverse.sh
。
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
void print_file_info(const char *path) {
struct stat statbuf;
if (stat(path, &statbuf) == -1) {
perror("stat");
return;
}
printf("File: %s\n", path);
printf("Size: %ld bytes\n", statbuf.st_size);
printf("Last modified: %s", ctime(&statbuf.st_mtime));
}
void traverse(const char *path) {
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return;
}
struct dirent *entry;
char full_path[1024];
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
if (S_ISDIR(statbuf.st_mode)) {
printf("Directory: %s\n", full_path);
traverse(full_path);
} else {
print_file_info(full_path);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
exit(EXIT_FAILURE);
}
traverse(argv[1]);
return 0;
}
编译运行:gcc -o file_info_readdir file_info_readdir.c
,然后执行./file_info_readdir /path/to/directory
。
snprintf
等函数正确构建路径,避免缓冲区溢出。opendir
、readdir
、stat
等函数的返回值进行适当处理。