Not quite. You need to call the ofstream constructor with the name, which can be a variable. Here is the ofstream() constructor's signature:
ofstream ( const char * filename, ios_base::openmode mode = ios_base::out );
So, as long as you construct the stream with a const char* file name, you are golden. Then, you can write to the ofstream object. Example:
void createAndWriteToFile( const char* vname, const char* somedata )
{
char fname[MAX_FILE_NAME_LEN];
// Construct file name here.
sprintf(fname, "test/%s", vname);
ofstream ostrm(fname);
ostrm.write(somedata, strlen(somedata));
}
rubberman
Posting Maven
2,572 posts since Mar 2010
Reputation Points: 365
Solved Threads: 306
Skill Endorsements: 52
Look more closely at ("test\" (variable+".txt").c_str() ).
You are missing something.
It's usually better to create complex strings in pieces rather than all in one line like this. Once you get the string generated properly, then start combining the terms.
WaltP
Posting Sage w/ dash of thyme
11,404 posts since May 2006
Reputation Points: 3,421
Solved Threads: 1,055
Skill Endorsements: 37
You need the header cstring for the C style function. string is for the C++ string object.
WaltP
Posting Sage w/ dash of thyme
11,404 posts since May 2006
Reputation Points: 3,421
Solved Threads: 1,055
Skill Endorsements: 37
I pretty much get what was posted (need to look up sprintf), but the code below gives me the error that "fname, MAX_FILE_NAME_LENGTH, and strlen"
Why have you started messing around with all this stuff? Your origininal idea was far superior; just that you made a careless typo. Fix that and move on to the next task at hand.
// ofstream write ("test\\" (variable+".txt").c_str() );
// this the place where I'm having trouble
ofstream write( ( "test\\" + variable + ".txt" ).c_str() ) ;
// you wouldn't have any trouble now
vijayan121
Posting Virtuoso
1,740 posts since Dec 2006
Reputation Points: 1,236
Solved Threads: 320
Skill Endorsements: 11
Not sure why the above suggestions were sprintf :S
string VariableString = "gsdgdsghas";
string FilePath = "test/" + VariableString + ".txt";
ofstream write(FilePath.c_str());
triumphost
Practically a Master Poster
625 posts since Oct 2009
Reputation Points: 59
Solved Threads: 55
Skill Endorsements: 1
Question Answered as of 8 Months Ago by
WaltP,
vijayan121,
triumphost
and 1 other