ICFS/test/opener/opener.c
2025-05-06 17:56:55 +02:00

87 lines
1.7 KiB
C

#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define PATH_MAX 4096
int main(int argc, char *argv[]) {
// Check for correct usage
if (argc != 2) {
fprintf(stderr, "Usage: %s <pathname>\n", argv[0]);
return 1;
}
const char *path = argv[1];
struct stat statbuf;
// Stat the given path to determine if it's a directory
if (lstat(path, &statbuf) == -1) {
perror("lstat");
return 1;
}
// Case 1: The path is not a directory
if (!S_ISDIR(statbuf.st_mode)) {
int fd = open(path, O_RDONLY);
if (fd == -1) {
perror("open");
return 1;
}
close(fd);
return 0;
}
// Case 2: The path is a directory
DIR *dirp = opendir(path);
if (dirp == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
int success = 1;
while ((entry = readdir(dirp)) != NULL) {
// Skip . and ..
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// Construct the full path
char fullpath[PATH_MAX];
snprintf(fullpath, PATH_MAX, "%s/%s", path, entry->d_name);
// Stat the entry to check if it's a regular file
struct stat entry_stat;
if (lstat(fullpath, &entry_stat) == -1) {
perror("lstat");
success = 0;
break;
}
// Only process regular files
if (!S_ISREG(entry_stat.st_mode)) {
continue;
}
// Try to open and immediately close the file
int fd = open(fullpath, O_RDONLY);
if (fd == -1) {
perror("open");
success = 0;
break;
}
close(fd);
}
closedir(dirp);
return (success ? 0 : 1);
}