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)
Registered users can post here. Sign in or register to post.