Shell Programming

Hello,

How can I do user input in my following shell command? right now it is working for any fixed value; however, if I want to input value (filename), it is showing "mv: cannot stat 'filename': No such file or directory"; how can I solve this issue? here is the portion of my code

else if ( command == "rename" )
{
cout << "Enter filename and newfilename" << endl;
cin >> filename >> newfilename;
system("mv filename newfilename");
}
Why do you run 'mv'? There is rename()
http://www.cplusplus.com/reference/cstdio/rename/


Explanation for your observed error: you call system() with one const string literal. One string. While it does appear to contain same characters as some variable identifiers in your program, it is entirely unrelated. You should have concatenated the values of variables with other strings in order to generate that one string.
1
2
3
4
5
6
7
8
9
cout << "Enter filename and newfilename" << endl;
std::string filename; 
std::string newfilename; 
cin >> filename >> newfilename;
std::string command("mv ");
command += filename;
command += " ";
command += newfilename;
system(command.c_str());


When you just put what you had, filename and newfilename are considered part of the string because they are inside of " " marks. How does the computer know if you're trying to put the literal meaning of "filename" or your variable? What you can do instead is concatenate strings to put the value of your variables instead of the literal text. The computer thinks you're trying to run the command mv filename newfilename, and looks for filename. Filename isn't a real file, but you put that string literal.

Edit: My post might be redundant, I didn't read all of keskiverto's reply.
Last edited on
Topic archived. No new replies allowed.