Search code examples
c++filefstreamnamingofstream

C++ ofstream dynamic file names and content


Trying to write a dynamic file name and content using fstream with the following:

ofstream file;
    file.open("./tmp/test.txt");
    //file.open("./tmp/%s.txt.txt", this->tinfo.first_name);    //nope file.open->FUBAR
    //file.open("./tmp/" + this->tinfo.first_name + ".txt");    //nope this->FUBAR
    //file.write( "%s\n", this->tinfo.first_name);              //nope this->FUBAR
    file << "%s\n", this->tinfo.first_name;                     //nope %s->FUBAR
    //Me->FUBU
    file << "test\n";
    file << "test\n";
    file.close();

I was naive enough to assume the printf (%d, this->foo) conventions will work, if not for the actual file name, then for the content.

Nothing seems to work, what am i missing?

just in case its something in my includes:

#include "stdafx.h"
//#include <stdio.h>    //redundant, as "stdafx.h" already includes it
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

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

Solution

  • You don't need %s this case, the ofstream will implicitly understand this->tinfo.first_name. So please replace this line

    file << "%s\n", this->tinfo.first_name;                     //nope %s->FUBAR
    

    by

    file << this->tinfo.first_name << "\n";                     //nope %s->FUBAR