How to use a filename string with fstream?

D

DellBoy

I would like to be able to do something like this:

string sFileInfo = "MyFile.tmp";
fstream InfoFile;
InfoFile.open(sFileInfo, fstream::app);
// >> do some i/o operations <<
InfoFile.close();
return 0;

How do I convert the filename string to the const char * that fstream
wants?
 
J

Johan

DellBoy said:
I would like to be able to do something like this:

string sFileInfo = "MyFile.tmp";
fstream InfoFile;
InfoFile.open(sFileInfo, fstream::app);
// >> do some i/o operations <<
InfoFile.close();
return 0;

How do I convert the filename string to the const char * that fstream
wants?

use sFileInfo.c_str()

Johan
 
M

Manfred

The method c_str() does this for you.
Example:
string sFileInfo = "MyFile.tmp";
fstream InfoFile;
InfoFile.open(sFileInfo, fstream::app);

InfoFile.open(sFileInfo.c_str(), fstream::app);
would be the replacement of the previous line.
// >> do some i/o operations <<
InfoFile.close();
return 0;

This should do it.

Manfred
 
P

Peter Julian

DellBoy said:
I would like to be able to do something like this:

string sFileInfo = "MyFile.tmp";
fstream InfoFile;
InfoFile.open(sFileInfo, fstream::app);
// >> do some i/o operations <<
InfoFile.close();
return 0;

How do I convert the filename string to the const char * that fstream
wants?

Google for a reference on the std::string class. You return a pointer to a
const char* with its c_str() member function. Thats just one of a long list
of interesting and handy functions.

// test.cpp
#include <iostream>
#include <fstream>
#include <string>

int main()
{
std::string s_filename( "data.dat" );
std::ifstream ifs;

ifs.open( s_filename.c_str() );
if ( !ifs )
{
std::cout << "error while opening " << s_filename;
std::cout << std::endl;
return 0;
}

std::string s_buffer;
std::vector<std::string> vs;
while ( std::getline( ifs, s_buffer ) )
{
vs.push_back( s_buffer );
}

if ( !ifs.eof() ) // if reason of termination != eof
{
std::cout << "error while reading file.\n";
return 0;
}

// do something with the vector of strings

return 0;
}
 
D

DellBoy

Thank you all for the help, and the effort put in to explain how the
solution would work with my code. Really excellent response. DellBoy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top