save readdir into a buffer in C

1.3k views Asked by At

I'm using readdir() to read to output all the files in a directory. The problem is that I need to save the strings into a buffer. Is there any way to save the output into a buffer or file descriptor etc?

Here is my code:

  DIR *directory;
  struct dirent *dir;

  directory = opendir();

  while ((dir = readdir(directory)) != NULL) {
    printf("%s\n", dir->d_name);
  }

  closedir(directory);
3

There are 3 answers

5
mchouhan_google On BEST ANSWER

Use scandir How to use scandir

It allocates the memory for you. Here is an example

/**code to print all the files in the current directory **/
struct dirent **fileListTemp;
char *path = ".";//"." means current directory , you can use any directory path here
int noOfFiles = scandir(path, &fileListTemp, NULL, alphasort);
int i;
printf("total: %d files\n",noOfFiles);
for(i = 0; i < noOfFiles; i++){
    printf("%s\n",fileListTemp[i]->d_name);

you can modify it to suit your need . Also do not forget to free memory allocated by scandir

0
rfermi On

In this case you will have to work with a data structure, like a linked list or a tree. Here's a short example, an idea to work on:

 pDir = readdir(directory);
 while ( pDir != NULL ){
   strcpy(dirStruct[iCtFile]->FileName, pp->d_name);
 }

Looking ahead, you should consider path treatment and other issues.

0
P.P On

Note that you'll need to pass a directory name to opendir().

This is simple example of how to read and save them into a buffer. It doubles the pointers every time it hits the limit. Modern operating systems will clean up the memory allocated once process dies. Ideally, you should also call free() in case of failures.

#include<stdio.h>
#include <dirent.h>
#include <sys/types.h>
#include<string.h>
#include<stdlib.h>

int main(void)
{
  size_t i = 0, j;
  size_t size = 1;
  char **names , **tmp;
  DIR *directory;
  struct dirent *dir;

  names = malloc(size * sizeof *names); //Start with 1

  directory = opendir(".");
  if (!directory) { puts("opendir failed"); exit(1); }

  while ((dir = readdir(directory)) != NULL) {
     names[i]=strdup(dir->d_name);
     if(!names[i]) { puts("strdup failed."); exit(1); }
     i++;
     if (i>=size) { // Double the number of pointers
        tmp = realloc(names, size*2*sizeof *names );
        if(!tmp) { puts("realloc failed."); exit(1); }
        else { names = tmp; size*=2;  }
     }
  }

  for ( j=0 ; j<i; j++)
  printf("Entry %zu: %s\n", j+1, names[j]);

  closedir(directory);
}