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

This topic is 4115 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## 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 on other sites
see opendir(3), readdir(3), scandir(3), rewinddir(3), etc. The API is Posix.

##### 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 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 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 on other sites
I came across this exact same problem a few days ago. Using boost::filesystem solved it for me.

1. 1
2. 2
3. 3
4. 4
Rutin
17
5. 5

• 11
• 37
• 12
• 12
• 11
• ### Forum Statistics

• Total Topics
631413
• Total Posts
2999945
×