Declare a Variable - then use it in System Call

Team...

Say my user gives a variable; can I use it in a system call?
I have tried with no love - so basically I take the user input and make a shell
file filled with the variables and then run it - then remove it. I feel it is an atrocious way to do business.

I would like to see the variable declared, assigned, placed in the call, executed.

like system("dd if=source of=target bs=512k")

Any ideas?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main(){

cout << "Give me the source" << endl;
string source;
cin >> source;
cout << "Give me the target" << endl;
string target;
cin >> target;
ofstream myfile;
myfile.open("hola.sh");
myfile << "dd if=" << source << " of=" << target << "bs=512k";
myfile.close();
system ("sh hola.sh && rm -rf hola.sh");
return main();
}
This is one of the most common questions found on the net. Did you look?

1
2
string cmd = "dd if=" + source + " of=" + target + " bs=512k";
system( cmd.c_str() );

I hope this helps.
I didn't. Thank you for your help; very clever!
Keep in mind that if source or target has spaces in the filename that the concatenated command will fail. In order to be bullet-proof you'll need to make sure that it gets properly quoted.

1
2
3
4
5
6
7
8
9
10
11
string quote( string s )
{
  string result;
  for (char c : s)
  {
    if (isspace( c ))
      result += '\\';
    result += c;
  }
  return result;
}
 
string cmd = "dd if=" + quote( source ) + " of=" + quote( target ) + " bs=512k";

Sorry, I probably should have mentioned this the first time.

Enjoy! :O)
Using system calls this way really puts your code into danger. With bigger programs, it creates a lot of errors that are really hard to be detected, unless you use one of those programs, such as checkmarx as help. Practicing on doing things without it might help in the future and that's why I recommend it.
Good luck.
depending on what you are actually doing, it may be worthwhile to have the actual shell script file out there with parameters instead of a full on c++ program. It just depends, but I believe everything you did here was doable in the scripting language, with no c++ needed at all. There is a break even point where things doable in scripting become easier in the c++, and then impossible to do in the script language, but this looks to be on the 'easier to do without c++ at all' side of that equation.

Topic archived. No new replies allowed.