Alex M. Alex M. - 9 months ago 27
C++ Question

c++ Fstream string combination error

I'm trying to make a function that writes a .ps1 script. I'm learning fstream functions and methods and I ran in to some troubles. I can't figure a way to make Fstream create the file at the given path (path1) and add in the same time a given name for the file and the extension.

void write(string s, string name) {

ostringstream fille;
fille << "$client = new-object System.Net.WebClient\n" << s;
string fil = fille.str();
ostringstream pat;
pat << path1 << "/" << ".ps1";
string path = pat.str();
fstream file(path);
if (file.open()) {
file << fil;
file.close();
}
}


I get the following error message (on the
if
line) during compilation:


no instance of overloaded function "
std::basic_fstream<_Elem, _Traits>::open
[with _Elem=
char
, _Traits=
std::char_traits<char>
]" matches the argument list

C2661 '
std::basic_fstream<char,std::char_traits<char>>‌​::open
': no overloaded function takes 0 arguments

Answer Source

First of all you don't use name parameter. Second you don't define path1 variable. And you do not need to call fstream::open method if you use fstream's initialization constructor.

    void write( const std::string & s, const std::string & name )
    {
         std::string fil("$client = new-object System.Net.WebClient\n");
         fil += s;

         std::ostringstream path;
         path << "C:/Folder/" << name << ".ps1";

         std::ofstream file( path.str() );
         if ( file.is_open() ) {
             file << fil;
             file.close();
         }
    }