How do you get a directory site listing in C?

Just how do you check a directory site for folders and also documents in C? It requires to be cross - system.

2019-12-02 02:56:52
Source Share
Answers: 5

Directory listing differs substantially according to the OS/platform present. This is because, numerous Operating systems utilizing their very own inner system phones call to attain this.

A remedy to this trouble would certainly be to seek a collection which conceals this trouble and also portable. However, there is no remedy that works with all systems faultlessly.

On POSIX suitable systems, you can make use of the collection to attain this making use of the code uploaded by Clayton (which is referenced initially from the Advanced Programming under UNIX publication by W. Richard Stevens). this remedy will certainly function under *NIX systems and also would certainly additionally work with Windows if you have actually Cygwin mounted.

Conversely, you can write a code to identify the underlying OS and afterwards call the ideal directory site listing function which would certainly hold the 'correct' means of detailing the directory site framework under that OS.

2019-12-03 01:19:01

There is no typical C (or C+npls) means to identify documents in a directory site.

Under Windows you can make use of the FindFirstFile/FindNextFile operates to identify all access in a directory site. Under Linux/OSX make use of the opendir/readdir/closedir features.

2019-12-03 01:06:59

The rigorous solution is "you ca n't", as the really principle of a folder is not absolutely go across - system.

On MS systems you can make use of _ findfirst, _ findnext and also _ findclose for a 'c' type of feeling, and also FindFirstFile and also FindNextFile for the underlying Win32 telephone calls.

Below is the C - FAQ solution :

2019-12-03 00:58:39

opendir/readdir are POSIX. If POSIX is not nearly enough for the transportability you intend to attain, examine Apache Portable Runtime

2019-12-03 00:58:33

The adhering to POSIX program will certainly publish the names of the documents in the existing directory site :

#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);
    perror ("Couldn't open the directory");

  return 0;

Credit :

Tested in Ubuntu 16.04.

2019-12-03 00:53:53