Sign in to follow this  
serratemplar

g++ (linux) - enumrate files in a directory

Recommended Posts

This seems like it should be a simple task, but so far I haven't been able to find anything (a lot of frustrating googling) that's lead me to an answer. Any of the solutions I've seen for C++ have all been for Windows (Visual C) and my current development platform is linux (Ubuntu), using g++. What library(ies?) have the functions I need to see what working directory I'm in and - ultimately - enumerate all of the folders/files I find within a starting folder (ideally recursing to deeper folders). If anybody can give me a link or something I would be truly excited. Thanks in advance.

Share this post


Link to post
Share on other sites
You could use the linux console commands pwd and ls to list what you need. pwd will spit out the current directory and calling ls like this:
ls -p -1 -L -R will print out files in each directory recursively. the -p switch will append a '/' to the end of the name if its a directory, the -L makes sure you don't get symbolic links (avoids symlink loops), the -1 makes the entries 1 per line and no additional information (ie. easy to parse) and the -R makes the command recursive.

Now to parse the output you can stream to a file using the '>' command - i don't think this is the best way. you could using the system command or a pipe or something?

Share this post


Link to post
Share on other sites
The following code snippet should sum it up:


dirent *filedata=NULL;
DIR *curdir = opendir(".");// opendir takes the dir path "." is current
if(NULL==fonts)
{
fprintf(stderr,"directory not found\n");
return false; // Handle appropiatelly?
}
while(NULL!=(filedata=readdir(fonts)))
{
// filedata->d_name contains a string to the current filename, including extension
}
closedir(curdir);




Edit: Forgot to mention, the code is POSIX, so I found that it compiles and runs on Windows using MinGW and probably would work on Cygwin, however I had to write a WinAPI equivalent for it to work on Visual C++, just in case [smile].

Share this post


Link to post
Share on other sites
This may be too obvious an answer, but the Boost Filesystem library offers cross-platform support for various common file operations, including iterating over the contents of a directory.

I believe boost::filesystem also offers a means of querying the current working directory, but I don't know that it offers a way to set the current working directory (although you didn't specifically mention needing to do this). Perhaps someone else will be able to clarify this.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this