user1978661
user1978661

Reputation: 1

How to use argv as variable

I would like to use a given Variable for my Main-function in c++ to be used as part of the name of the outputfile. The code is:

int main(int argc, char* argv[]) {
fstream f,g;
string s1,s2,name;
name = argv[5];

s1 = name+("_systemvalues.dat");
f.open(s1.c_str(), ios::out);
...
c.close();

An, for example, argv[5] should be "test". The program is compiling and it is running as well, but the output file is not produced. I can display s1 on the terminal and it is what it should be - but the outputfile is simply not produced.

Upvotes: 0

Views: 1557

Answers (2)

user1978661
user1978661

Reputation: 1

Ok... the problem was the input. The character '/' cannnot be used as part of a filename - with hindsight it is really clear.

Upvotes: 0

gifnoc-gkp
gifnoc-gkp

Reputation: 1516

Maybe you don't have the required write permissions to make changes to the filesystem / directory.

chmod -R 777 mydir

By the way you could use std::ofstream for the job. It will create the file for you if it doesn't already exist.

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

   /* ... */

   std::string name = "";
   name.append(argv[5]);
   name.append("_systemvalues.dat");

   std::ofstream out(name.c_str());

   out << "text" << std::endl;

   out.close();

   /* ... */

Upvotes: 1

Related Questions