Listing directory contents programmatically in Linux requires POSIX directory stream functions from <dirent.h>. Opening a directory handle with opendir() allows iterating through directory entries via readdir().
Directory Traversal C Code Example
#include <stdio.h>
#include <dirent.h>
#include <string.h>
int main(void) {
DIR *dir = opendir(".");
struct dirent *entry;
if (dir == NULL) {
perror("Unable to open current directory");
return 1;
}
printf("Directory Contents:\n");
while ((entry = readdir(dir)) != NULL) {
// Skip current (.) and parent (..) directory entries
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// Display file name and inode number
printf(" [%s] Inode: %ld\n", entry->d_name, (long)entry->d_ino);
}
closedir(dir);
return 0;
}
Comments and corrections