Created
August 13, 2024 02:28
-
-
Save luciditee/35660fb3eecd309c4d24947e389e8d64 to your computer and use it in GitHub Desktop.
Cross-platform (POSIX and Win32) recursive directory and file traversal example in C99
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Recursive directory and file traversal | |
// I don't make any claim to the code below, as it's hacked together from various publicly-available examples | |
// Targeting gnu99/c99 | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#ifdef _WIN32 | |
#include <windows.h> | |
#else | |
#include <dirent.h> | |
#include <sys/stat.h> | |
#endif | |
void traverse_directory(const char *dir_path) { | |
#ifdef _WIN32 | |
WIN32_FIND_DATA find_data; | |
HANDLE hFind; | |
char search_path[1024]; | |
snprintf(search_path, sizeof(search_path), "%s\\*", dir_path); | |
hFind = FindFirstFile(search_path, &find_data); | |
if (hFind == INVALID_HANDLE_VALUE) { | |
fprintf(stderr, "Error opening directory: %s\n", dir_path); | |
return; | |
} | |
do { | |
if (strcmp(find_data.cFileName, ".") == 0 || strcmp(find_data.cFileName, "..") == 0) { | |
continue; | |
} | |
char path[1024]; | |
snprintf(path, sizeof(path), "%s\\%s", dir_path, find_data.cFileName); | |
if (find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { | |
printf("Directory: %s\n", path); | |
traverse_directory(path); | |
} else { | |
printf("File: %s\n", path); | |
} | |
} while (FindNextFile(hFind, &find_data) != 0); | |
FindClose(hFind); | |
#else | |
struct dirent *entry; | |
DIR *dp = opendir(dir_path); | |
if (dp == NULL) { | |
perror("opendir"); | |
return; | |
} | |
while ((entry = readdir(dp))) { | |
char path[1024]; | |
struct stat statbuf; | |
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { | |
continue; | |
} | |
snprintf(path, sizeof(path), "%s/%s", dir_path, entry->d_name); | |
if (stat(path, &statbuf) == -1) { | |
perror("stat"); | |
continue; | |
} | |
if (S_ISDIR(statbuf.st_mode)) { | |
printf("Directory: %s\n", path); | |
traverse_directory(path); | |
} else { | |
printf("File: %s\n", path); | |
} | |
} | |
closedir(dp); | |
#endif | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment