I'm writing a program in C++ which do some special treatment for all the files in the current directory on Linux OS.
So i was thinking of using system calls such as system("ls")
to get the list of all files.
but how to store it then inside my program ? ( how to redirect the output of ls to let's say a string that i declared in the program )
Thanks
I suggest you don't call out to ls
- do the job properly, using opendir/readdir/closedir
to directly read the directory.
Code example, print directory entries:
// $ gcc *.c && ./a.out
#include <stdlib.h> // NULL
#include <stdio.h>
#include <dirent.h>
int main(int argc, char* argv[]) {
const char* path = argc <= 1 ? "." : argv[1];
DIR* d = opendir(path);
if (d == NULL) return EXIT_FAILURE;
for(struct dirent *de = NULL; (de = readdir(d)) != NULL; )
printf("%s/%s\n", path, de->d_name);
closedir(d);
return 0;
}