Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get a directory listing in C?

How do you scan a directory for folders and files in C? It needs to be cross-platform.

like image 463
andrewrk Avatar asked Aug 15 '08 17:08

andrewrk


People also ask

What is directory in C language?

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.

How can I get the list of files in a directory using C ++?

Use opendir/readdir Functions to Get a List of Files in a Directory.


2 Answers

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.

like image 165
Clayton Avatar answered Nov 02 '22 05:11

Clayton


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

like image 27
Will Dean Avatar answered Nov 02 '22 05:11

Will Dean