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);
				
                        
Use scandir How to use scandir
It allocates the memory for you. Here is an example
you can modify it to suit your need . Also do not forget to free memory allocated by scandir