[英]How can we check if a given input is a valid system command like "ls" or "cd" in c program?
我正在编写将“ls”或“cd”等系统命令作为输入的 ac 程序。但是,用户可以给出任何类型的命令,其中有些命令不是命令。我如何才能找到哪些命令有效,哪些无效?我正在 Ubuntu 中编写代码。
Off the top of my head there are two ways to check if the input is a valid system command, without actually attempting to run it:在我的脑海里,有两种方法可以检查输入是否是有效的系统命令,而无需实际尝试运行它:
A long list of if()
s and else if()
s which strcmp()
the input string with a hard-coded, predetermined list of valid commands - this may be relatively slow, both to write and to run, but with conditional-compilation with #ifdef
, can be nearly perfectly portable (ie, can be made to work with Windows, Linux, BSD et all from one codebase with enough hard work).一长串
if()
s 和else if()
s,其中strcmp()
输入字符串与硬编码的、预先确定的有效命令列表 - 这可能相对较慢,无论是写入还是运行,但有条件 -使用#ifdef
编译,几乎可以完美移植(即,只要付出足够的努力,就可以从一个代码库中使用 Windows、Linux、BSD等)。
If you don't mind being restricted to a UNIX-like platform only, parse the $PATH
variable, and search for executables with the same filename as the input string in the directories found from $PATH
, and handle errors if no match is met.如果您不介意仅限于类 UNIX 平台,请解析
$PATH
变量,并在从$PATH
找到的目录中搜索与输入字符串具有相同文件名的可执行文件,如果不匹配则处理错误.
You may wish to implement a hybrid of 2.
and 1.
by hard-coding some exceptions which may not be found in $PATH
.您可能希望通过硬编码一些
$PATH
可能找不到的异常来实现2.
和1.
的混合。
IMHO, however, I fail to see why you would want to do this;恕我直言,但是,我不明白您为什么要这样做; it seems puzzling to me.
这对我来说似乎令人费解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.