在 CentOS 中,readdir 函数可能会遇到一些常见错误
fcntl
函数检查文件描述符是否有效。#include <unistd.h>
#include <fcntl.h>
int main() {
int fd = open("file.txt", O_RDONLY);
if (fd == -1) {
perror("open");
return 1;
}
struct stat sb;
if (fstat(fd, &sb) == -1) {
perror("fstat");
close(fd);
return 1;
}
if (!S_ISREG(sb.st_mode)) {
fprintf(stderr, "Not a regular file\n");
close(fd);
return 1;
}
close(fd);
return 0;
}
DIR *dir = opendir("directory");
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// Process the directory entry
}
closedir(dir);
DIR *dir = opendir("directory");
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// Process the directory entry
// Simulate memory allocation failure
if (entry->d_name == NULL) {
fprintf(stderr, "Memory allocation failed\n");
continue;
}
}
closedir(dir);
DIR *dir = opendir("directory");
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// Process the directory entry
// Check for illegal entries
if (entry->d_name[0] == '\0' || entry->d_name[strlen(entry->d_name) - 1] == '\0') {
fprintf(stderr, "Illegal directory entry: %s\n", entry->d_name);
continue;
}
}
closedir(dir);
遵循这些建议,你应该能够解决 CentOS 中 readdir 的常见错误。如果你遇到其他问题,请随时提问。