Search code examples
c++cstringfile-pointerchar-pointer

Why do I get an error when passing a string as a filename, but not a char*?


I understand that a char pointer is used to create strings in C (with a null terminator). But I don't understand why I am getting an error in C++ for passing a string as a file name, yet it works for a char*.

The h prototype and cpp function signatures have matched for both scenarios.

I have included some code excerpt and all the includes I have for this 'utility' file (I have a few other functions in it besides the read and write ones.

//from the header includes

#include <string>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <limits>
#include <cctype>
#include <cstdlib>



//from the cpp file


//this one throws and error!
void readFiles(string fileName1)
{

    ifstream file1;
    file1.open(fileName1);

    //to do implement read...

}

//This one works
void readFiles(char* fileName1)
{

    ifstream file1;
    file1.open(fileName1);
    //to do implement read...

}

The error I get is:

no matching function for std::basic_ofstream::open(std::string&)

I've also tried passing by reference and pointer to the string. Is this because the file name is only read as a char array, some hang over from C?


Solution

  • This is the signature of open on ifstream:-

    void open (const char* filename,  ios_base::openmode mode = ios_base::in);
    

    So, passing string won't work.

    You can do

    std::string str("xyz.txt");
    readFile( str.c_str() )
    

    However, in C++11 there are two overloads:-

    void open (const string& filename,  ios_base::openmode mode = ios_base::in);
    void open (const   char* filename,  ios_base::openmode mode = ios_base::in);
    

    Had you been with C++11, there would have been one less post on stack overflow...