Search code examples
c++boostboost-filesystem

How to access the string representation of boost filesystem's path class, and remove the quotes


I want to save the path to the files in a dir as a string. The example from the tutorial pretty much does what I want except that it does it with the quotation marks which I want to be removed. Now I know that I can do it by adding .string() to the path but I simply don't know where to put it in this example.

Hope someone can help me with that.


Solution

  • As you said you need to use .string() method on path to output without quotation marks. Below the modified tutorial example outputting no quotation marks:

    #include <iostream>
    #include <iterator>
    #include <algorithm>
    #include <boost/filesystem.hpp>
    using namespace std;
    using namespace boost::filesystem;
    
    int main(int argc, char* argv[])
    {
        if (argc < 2)
        {
            cout << "Usage: tut3 path\n";
            return 1;
        }
    
        path p(argv[1]);   // p reads clearer than argv[1] in the following code
    
        try
        {
            if (exists(p))    // does p actually exist?
            {
                if (is_regular_file(p))        // is p a regular file?
                    cout << p.string() << " size is " << file_size(p) << '\n';
    
                else if (is_directory(p))      // is p a directory?
                {
                    cout << p.string() << " is a directory containing:\n";
    
                    for (directory_iterator it(p); it != directory_iterator(); ++it)
                        cout << it->path().string() << "\n";
                }
                else
                    cout << p.string() << " exists, but is neither a regular file nor a directory\n";
            }
            else
                cout << p.string() << " does not exist\n";
        }
    
        catch (const filesystem_error& ex)
        {
            cout << ex.what() << '\n';
        }
    
        return 0;
    }