带有用户定义输入的c++ Robocopy
C++ Robocopy with userdefined inputs
我是c++的初学者,目前正在尝试编写一个小程序来帮助网络设备的自动复制备份,到目前为止,我已经提出了以下代码,但是当我试图编译时,我得到以下错误:
31没有匹配'operator<<' in '"ROBOCOPY//" <<oldname '
我得到相同的错误重复所有行使用robocopy,任何帮助将不胜感激。谢谢所有的
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
string oldname;
string newname;
string userid;
char response;
cout<<"Please input old device name eg XXXXXXn";
cin>> oldname;
cout<<"Please input new device name eg XXXXXXn";
cin>> newname;
cout<<"Please input userid eg SP12345n";
cin>> userid;
cout<<"Does your current device contain a D: drive? Y or N?";
cin>> response;
if (response == 'Y')
{
std::system("ROBOCOPY //"<<oldname<<"/c$/Users/"<<userid<<"/Desktop //"<<newname<<"/C$/Users/"<<userid<<"/Desktop /MIR /w:0 /r:0");
std::system("ROBOCOPY //"<<oldname<<"/c$/Users/"<<userid<<"/Favorites //"<<newname<<"/C$/Users/"<<userid<<"/Favorites /MIR /w:0 /r:0");
std::system("ROBOCOPY //"<<oldname<<"/c$/Users/"<<userid<<"/My Documents //"<<newname<<"/C$/Users/"<<userid<<"/My Documents /MIR /w:0 /r:0");
std::system("ROBOCOPY //"<<oldname<<"/d$ //"<<newname<<"/C$/Users/"<<userid<<"/Desktop/D backup /MIR /w:0 /r:0";
}
else if (response == 'N')
{
std::system("ROBOCOPY //"<<oldname<<"/c$/Users/"<<userid<<"/Desktop //"<<newname<<"/C$/Users/"<<userid<<"/Desktop /MIR /w:0 /r:0;
std::system("ROBOCOPY //"<<oldname<<"/c$/Users/"<<userid<<"/Favorites //"<<newname<<"/C$/Users/"<<userid<<"/Favorites /MIR /w:0 /r:0;
std::system("ROBOCOPY //"<<oldname<<"/c$/Users/"<<userid<<"/My Documents //"<<newname<<"/C$/Users/"<<userid<<"/My Documents /MIR /w:0 /r:0;
}
system("pause");
}
首先,这个简单的语句不起作用:
std::string str;
system(str); //<== expecting C-string
因为system
需要一个以空结尾的C-string,而std::string
不需要。如果添加text:
system("text" + str);
编译器不知道该怎么处理。
其次,system
不能正常传递命令行参数。您需要CreateProcess
或ShellExecuteEx
您可能还必须传递应用程序的完整路径。例子:
#include <iostream>
#include <string>
#include <sstream>
#include <Windows.h>
void foo(std::string userid, std::string oldname, std::string newname)
{
std::stringstream ss;
ss << "c:\Program Files (x86)\Full Path\Robocopy.exe"
<< " /c:\users\" << userid << "\Desktop\" << oldname
<< " /c:\users\" << userid << "\Desktop\" << newname
<< " /MIR /w:0 /r:0";
std::string commandLine = ss.str();
//examine the commandline!
std::cout << commandLine << "n";
STARTUPINFOA si;
PROCESS_INFORMATION pi;
memset(&si, 0, sizeof(si));
si.cb = sizeof(si);
memset(&pi, 0, sizeof(pi));
char *buf = _strdup(commandLine.c_str());
CreateProcessA(0, buf, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
free(buf);
}
int main()
{
foo("x", "y", "z");
return 0;
}