-1

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?

  • 2
    You need C++11 for that overload. See http://en.cppreference.com/w/cpp/io/basic_ifstream/open. – juanchopanza Nov 03 '14 at 15:16
  • 1
    Or you can use `fileName1.c_str()`. – Yeraze Nov 03 '14 at 15:17
  • 1
    In pre-modern C++ (C++03 and before), `std::fstream`'s constructor takes a `const char *`, and not an `std::string`. A `string` version is available in C++11 and later. – The Paramagnetic Croissant Nov 03 '14 at 15:18
  • 1
    It's pretty normal for courses to lag behind. It takes time for textbooks, lectures, assignments, etc. to be updated; for fully-compliant tools to be released; and for those tools to be rolled out to lab workstations. – nobody Nov 03 '14 at 15:24

1 Answers1

4

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...

ravi
  • 10,994
  • 1
  • 18
  • 36