[英]Using a system command with parameter from program in C++
So I'm doing a project for school and was trying to use the windows function "mkdir", but the directory name would be a string given by the program. 因此,我正在为一个学校做一个项目,并试图使用Windows函数“ mkdir”,但是目录名称将是程序指定的字符串。 Here's the (not very useful) code:
这是(不是很有用)的代码:
string c,a;
cin>>c;
if(c.compare("mkdir")==0)
cin>>a;
system("mkdir"); //here I want to make the directory
}
As others have mentioned, it would be better to create the directory without using the system
call. 正如其他人提到的那样,最好在不使用
system
调用的情况下创建目录。 If you would like to use that method regardless, you need to build a command string which includes your arguments prior to passing it to system
. 如果无论如何都要使用该方法,则需要先构建一个包含参数的命令字符串,然后再将其传递给
system
。
char command[100];
sprintf(command, "mkdir %s", a);
system(command);
Directories don't exist for the C++11 (or C++14) standard. C ++ 11(或C ++ 14)标准不存在目录。 Later C++ standard (eg C++17 ...) might offer the std::filesystem library.
更高的C ++标准(例如C ++ 17 ...)可能会提供std :: filesystem库。
You could use operating system specific primitives. 您可以使用特定于操作系统的原语。 On Linux and POSIX, consider the mkdir(2) system call (and CreateDirectory function on Windows).
在Linux和POSIX上,请考虑mkdir(2)系统调用(在Windows上为CreateDirectory函数)。
You could find framework libraries (eg POCO , Qt , Boost , ....) wrapping these, so with these libraries you won't care about OS specific functions. 您可以找到包装这些的框架库(例如POCO , Qt , Boost ,....),因此使用这些库就不必关心操作系统特定的功能。
but the directory name would be a string given by the program.
但是目录名称将是程序指定的字符串。
Then you could consider building a command as a runtime C string for system(3) . 然后,您可以考虑将命令构建为system(3)的运行时C字符串。 Eg with snprintf(3) (or with some
std::string
operation). 例如,使用snprintf(3) (或某些
std::string
操作)。 Beware of code injection (eg think of the malicious user providing /tmp/foo; rm -rf $HOME
as his directory name on Linux)! 当心代码注入 (例如,将恶意用户提供
/tmp/foo; rm -rf $HOME
作为Linux上的目录名)!
如果要使用WinApi创建文件夹,请参见CreateFolder
The simplest solution I can think of: 我能想到的最简单的解决方案:
string c;
cin >> c;
if(c == "mkdir") {
string a;
cin >> a;
system("mkdir " + a);
}
But if this project involves writing some kind of command shell, system
is very likely off-limits and you're expected to use the operating system's API directly. 但是,如果该项目涉及编写某种命令外壳,那么
system
很可能会超出限制,您应该直接使用操作系统的API。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.