CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 14 of 14
  1. #1
    Join Date
    Jan 2011
    Location
    U.S. of A
    Posts
    13

    list all files in a directory c++

    Hi!
    So, I need to list all the files in the current directory, i have tried several methods but i keep getting this error: cannot convert `std::basic_string<char, std::char_traits<char>, std::allocator<char> >' to `const char*' for argument `1' to `int system(const char*)'
    What is the best method to do this?

    In any case, heres what i have so far...

    #include <stdlib.h>
    #include <string>
    using namespace std;

    int main(int argc, char *argv[])
    {
    system("DIR "+ExePath());
    system("PAUSE");
    return 0;
    }

    string ExePath() {
    char buffer[MAX_PATH];
    GetModuleFileName( NULL, buffer, MAX_PATH );
    string::size_type pos = string( buffer ).find_last_of( "\\/" );
    return string( buffer ).substr( 0, pos);
    }

    Thanks in Advance!
    -0M3G4

  2. #2
    Join Date
    Apr 2008
    Posts
    118

    Re: list all files in a directory c++

    What do you mean by "best"? The code you have posted will work on any system that recognises the DIR command in the shell (once you solve that string to char* problem). Which, I think, is windows.

    The last time I had to do this, I used the dirent.h header file and the readdir function, but dirent.h is POSIX and isn't part of windows.

    I think windows makes use of FindFirstFile and FindNextFile to do something similar.

    What happens if you try to build that system command in pieces?

    Something like:

    Code:
    std::string commandPart;
    commandPart = ExePath();
    std::string command("DIR ");
    command = command + commandPart;
    const char* command_cStr = command.c_str();
    system(command_cStr);
    Last edited by Moschops; January 19th, 2011 at 12:12 PM.

  3. #3
    Join Date
    Jan 2011
    Location
    U.S. of A
    Posts
    13

    Re: list all files in a directory c++

    the problem is the above code returns an error
    best i meant most efficient
    this is a windows program

    there is a version of dirent.h for windows here: http://users.cs.fiu.edu/~weiss/cop4338/dirent.h
    but i could not get it working either... Any working sample code would be appreciated

  4. #4
    Join Date
    Apr 2008
    Posts
    118

    Re: list all files in a directory c++

    Quote Originally Posted by 0M3G4 View Post
    Any working sample code would be appreciated
    http://en.wikipedia.org/wiki/Dirent.h

    The error you listed above indicates that you have a std::String, and you're trying to feed it to something that expects a const char*. This makes sense, as you are using the operator '+' on a char* and a std::string, and the return from that is a std::string, which you are then trying to feed to the system command, which expects a const char*.

    Look at the std::string member function c_str()
    Last edited by Moschops; January 19th, 2011 at 12:19 PM.

  5. #5
    Join Date
    Jan 2011
    Location
    U.S. of A
    Posts
    13

    Re: list all files in a directory c++

    Heres an exe of the above code you gave me, it works, but it says Cannot Find Specified Path?
    Even though the path is correct... I'm about to try dirent.h, ill reply whether or not i have any success
    Attached Files Attached Files

  6. #6
    Join Date
    Apr 2008
    Posts
    118

    Re: list all files in a directory c++

    Quote Originally Posted by 0M3G4 View Post
    Heres an exe of the above code you gave me, it works, but it says Cannot Find Specified Path?
    Even though the path is correct... I'm about to try dirent.h, ill reply whether or not i have any success
    How do you know the path is correct? If it cannot find the specified path, that would imply that the path must be incorrect.

  7. #7
    Join Date
    Jan 2011
    Location
    U.S. of A
    Posts
    13

    Re: list all files in a directory c++

    Quote Originally Posted by Moschops View Post
    How do you know the path is correct? If it cannot find the specified path, that would imply that the path must be incorrect.
    I think its getting stuck on the spaces because if i try doing a dir of for exampleC:\Documents and Settings\Guest\Application Data\Mozilla\Firefox it'll report cannot find path specified but C:\unervx\docs will work perfectly :P
    I dont know, going to try dirent.h

  8. #8
    Join Date
    Apr 2008
    Posts
    118

    Re: list all files in a directory c++

    Have you tried typing

    dir c:\Program Files

    on your windows command line? It won't work.

    If you include spaces, you need to wrap it in quotes.

    dir "c:\Program Files"

    This might do it. If you add a std::cout in the right place you can see what command is actually being passed to system.

    Code:
    command = "\"" + command + commandPart + "\"";

  9. #9
    Join Date
    Jan 2011
    Location
    U.S. of A
    Posts
    13

    Re: list all files in a directory c++

    Quote Originally Posted by Moschops View Post
    Have you tried typing

    dir c:\Program Files

    on your windows command line? It won't work.

    If you include spaces, you need to wrap it in quotes.

    dir "c:\Program Files"

    This might do it. If you add a std::cout in the right place you can see what command is actually being passed to system.

    Code:
    command = "\"" + command + commandPart + "\"";
    YAY! That did the trick
    Thanks For Your Help!
    Final Code:
    Code:
    #include <stdlib.h>
    #include <string>
    #include <C:\Documents and Settings\Justin\workspace\Basic Library\basic.h>
    using namespace std;
    
    int main(int argc, char *argv[])
    {
    std::string commandPart;
    commandPart = ExePath();
    std::string command("DIR ");
    command = command + "\"" + commandPart + "\"";
    const char* command_cStr = command.c_str();
    print(command_cStr);
    system(command_cStr);
    system("PAUSE");
    }
    -0M3G4

  10. #10
    Join Date
    Jan 2011
    Location
    U.S. of A
    Posts
    13

    Re: list all files in a directory c++

    Final Compiled EXE Attached For Possible Future Reference...
    Attached Files Attached Files

  11. #11
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: list all files in a directory c++

    For an easy-to-use and cross-platform library for doing such things, I recommend Boost.Filesystem. I'm not sure whether it's going to be included in C++0x or not.

  12. #12
    Join Date
    Oct 2009
    Posts
    577

    Smile Re: list all files in a directory c++

    You could make a 'system("dir .");' to list the current directory. As long as your program wouldn't do a change of the working directory programmatically, the folder listed is the one where the executable resides.

    You also could do 'system("dir . >> dir.txt");' what redirects the output to file dir.txt (which also is in the current folder). After that you could open the dir.txt and make a customized output or apply a filtering of the files listed or do whatever you want. I sometimes write batch files this way by using the files listed as input for further commands.

    An alternative to the system command is to using FindFirstFile and FindNextFile of WINAPI.

    You would find a lot of code samples of that but for your case it is as simple as

    Code:
    WIN32_FIND_DATA fd = { 0 };
    HANDLE hf = FindFirstFile("*.*", &fd);
    if (hf == INVALID_HANDLE_VALUE) return GetLastError();
    do 
    {
        std::cout << fd.cFileName << std::endl;
    
    } while (FindNextFile(hf, &fd));

  13. #13
    Join Date
    Jan 2009
    Posts
    1,689

    Re: list all files in a directory c++

    Try this:

    Code:
    #include <dirent.h>
    
    static bool Exists(const string & name){
        if (DIR * dir = opendir(name.c_str())){
    	   closedir(dir);
    	   return true;
        }
        return false;
    }
    
    //name should include the final slash
    static bool GetAllFiles(const string & name, vector<string> & res, bool recurse){
        if (DIR * dir = opendir(name.c_str())){
    	   struct dirent * dp;
    	   if (!(dp = readdir(dir))) return false;  //.
    	   if (!(dp = readdir(dir))) return false;  //..
    	   while(dp = readdir(dir)){
    		  const string str = name + dp -> d_name;
    		  if (Exists(str + "/")){
    			 if (recurse) GetAllFiles(str + "/", res, true);
    		  } else {
    			 res.push_back(str);
    		  }
    	   }
    	   closedir(dir);
    	   return true;
        }
        return false;
    }
    Works really well, you should only have problems if dirent.h doesn't exist, but it should be there on all *nix systems and MinGW. I'm not entirely sure if you have to free readdir or not :/ Can someone confirm that you don't have to? I think it's one of those things like ctime where you don't have to.
    Last edited by ninja9578; January 19th, 2011 at 06:35 PM.

  14. #14
    Join Date
    Apr 2008
    Posts
    725

    Re: list all files in a directory c++

    Quote Originally Posted by Lindley View Post
    For an easy-to-use and cross-platform library for doing such things, I recommend Boost.Filesystem. I'm not sure whether it's going to be included in C++0x or not.
    indeed. boost:filesystem will look much cleaner.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured