Hello,
I am new to Linux and is wondering how to read all files in the ./ directory (i.e. local) directory in alphabetical order in C++. I am aware of opendir() but how do you state that you want to read from the local directory. Any advice will be greatly appreciated!!!
#include <algorithm>
#include <string>
#include <vector>
#include <dirent.h>
#include <sys/types.h>
// read_directory()
// Return an ASCII-sorted vector of filename entries in a given directory.
// If no path is specified, the current working directory is used.
//
// Always check the value of the global 'errno' variable after using this
// function to see if anything went wrong. (It will be zero if all is well.)
//
std::vector <std::string> read_directory( const std::string& path = std::string() )
{
std::vector <std::string> result;
dirent* de;
DIR* dp;
errno = 0;
dp = opendir( path.empty() ? "." : path.c_str() );
if (dp)
{
while (true)
{
errno = 0;
de = readdir( dp );
if (de == NULL) break;
result.push_back( std::string( de->d_name ) );
}
closedir( dp );
std::sort( result.begin(), result.end() );
}
return result;
}
Thanks!! This helped alot!! However, I have another question, if I go the above route will I be able to concatenate all files and parse the concatenated files and strip out all valid email addresses or do I need to go another way. Because I am thinking that the above way will just give me the filenames!! But while getting the filenames, is it posible to read the file and write it to one big temp file(which will be a file of all files). After reading and writng all files, the temp file can be read and all valid email addresses can be stipped out. Do you think this will work? If this will work, how do you read a file in linux. Once again thanks! Any advice will be greatly appreciated!!!
Once again thanks!! After having time to look at your example(above) in detail, I have a couple of questions? First, if you have dp = opendir( ) instead of the above line, the search will be on the current/local directory,correct. Second, I don't understand the de->d_name in the following line of code: result.push_back( std::string( de->d_name ) ), exactly what is d_name? Your respone is greatly appreciated!!