This is for the more experienced folks.

Recently I found that in Visual C++ 2010 (and 2012, not sure about earlier versions) one can use a std::string as the file name argument for the .open( ) function. I've always known the .open( ) function to take only char* (C-style) strings as the argument. Use of std::string would require the use of the .c_str( ) method.

Anyone have any idea when this showed up in VC++? And why MS doesn't seem to document it?

Example code

#include <iostream>
#include <fstream>
#include <string>

using namespace std;
int main ()
    string fname = "test.txt";
    ifstream fin;

    fin.open( fname );    //previously, this had to be: fin.open( fname.c_str( ) );

    if( ! fin )
        cout << "Error." << endl;

    fin.close( );

    return 0;
5 Years
Discussion Span
Last Post by NathanOliver

I'm pretty sure the std::string overload was added in C++0x. I can only imagine they didn't add it earlier o prevent a dependancy between the <string> and <fstream>. I haven't been able to find an official statement about why they made the choice to add it in C++0x, although I'm sure it somewhere..

Section of a 2010 draft of the C++0x standard (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3092.pdf) contains the function declaration.

Edited by Gonbe


Well, you could probably go through the minutes of the committee meetings, but I think in this case the rationale is pretty obvious. It's closing an consistency hole in the standard library where there's not an overload for both C-style strings and C++ strings.


I don't use VS at the moment, but is it still backwards compatible? Can I still give a c-style-string to .open()?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.