How do you scan a directory for folders and files in C? It needs to be cross-platform.
Special C language functions are available to read and manipulate directories, which helps your programs manage files and do other fun file stuff. A directory is really a special type of file, a data container that acts as a database referencing other files stored on the media.
Use opendir/readdir Functions to Get a List of Files in a Directory.
The following POSIX program will print the names of the files in the current directory:
#define _XOPEN_SOURCE 700 #include <stdio.h> #include <sys/types.h> #include <dirent.h> int main (void) { DIR *dp; struct dirent *ep; dp = opendir ("./"); if (dp != NULL) { while (ep = readdir (dp)) puts (ep->d_name); (void) closedir (dp); } else perror ("Couldn't open the directory"); return 0; }
Credit: http://www.gnu.org/software/libtool/manual/libc/Simple-Directory-Lister.html
Tested in Ubuntu 16.04.
The strict answer is "you can't", as the very concept of a folder is not truly cross-platform.
On MS platforms you can use _findfirst, _findnext and _findclose for a 'c' sort of feel, and FindFirstFile and FindNextFile for the underlying Win32 calls.
Here's the C-FAQ answer:
http://c-faq.com/osdep/readdir.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With