Is there a better way to get data returned by 'ls' command instead of
'system("ls > file.txt");' and then reading the file. I'm thinking of
something that would return 'const char *' into my buffer.
Dear Matko,
I know of no standard C++-specific way of doing this, but I do know
you can use the C functions opendir() and readdir() to do this.
Read the documentation for those functions for details, but in a
nutshell, opendir() returns a DIR*, which can then be passed into
readdir() multiple times, each time returning a dirent*. This dirent
object has a d_name member which points to the filename (essentially
the char* you're looking for).
Here's a short sample program to get you started:
#include <dirent.h> // for opendir(), readdir(), and closedir()
#include <iostream>
int main(int argc, char ** argv)
{
DIR *dir = opendir("."); // open the current directory
if (!dir)
{
std::cerr << "Cannot open directory!" << std::endl;
exit(1);
}
struct dirent *entry;
while (entry = readdir(dir)) // notice the single '='
{
std::cout << "Found directory entry: "
<< entry->d_name << std::endl;
}
closedir(dir);
return 0;
}
After creating the DIR*, remember to check to make sure it is non-
NULL before using it with readdir(). Do not free (or delete) the DIR
and dirent handles, but remember to close the DIR handle with closedir
() or it will remain open for the rest of your program.
Eventually readdir(dir) will return NULL, which lets you know it is
done returning dir entries. If you want more details, I urge you to
read those functions' documentation.
Many third-party C++ libraries (like Trolltech's Qt) have cleaner
(and more C++-oriented) ways of getting directory entries. If you
have access to one, I recommend using it. If you can't, opendir() and
readdir() are quite portable and should suit your needs.
Thank you. And God bless you, too!
-- Jean-Luc