Search code examples
c++visual-c++boostpathboost-filesystem

Issue getting `boost::filesystem::path` character pointer


Of the two following lines, the first one gives me a compile time error, the second is fine:

    std::remove( boost::filesystem::path( mypath / "file.log" ).c_str() );
    std::remove( boost::filesystem::path( mypath / "file.log" ).string().c_str() );

The std::remove signature is: int remove( const char* fname );

This is the error message:

"No instance of overloaded function "std::remove" matches the argument list"

But both boost::filesystem::path::c_str() and std::string::c_str() return a const char*.

The compiler I am using is Visual C++ 2013.


Solution

  • But both boost::filesystem::path::c_str() and std::string::c_str() return a const char*

    no, this is not true.

    We can open boost\filesystem\path.hpp source code and see what is going on there:

      template< typename Char, Char Separator, Char PreferredSeparator, Char Dot >
      struct path_constants
      {
        typedef path_constants< Char, Separator, PreferredSeparator, Dot > path_constants_base;
        typedef Char                                    value_type; // <---
        //...
      };
    
      class path :
        public filesystem::path_detail::path_constants<
    #ifdef BOOST_WINDOWS_API
          wchar_t, L'/', L'\\', L'.'  // [1]
    #else
          char, '/', '/', '.'
    #endif
        >
      {
    

    and in [1] line wchar_t is passed as first argument Char to path_constants template, so under Windows c_str returns pointer to wide character (2 bytes).