我正在用 C 编写一个函数/方法,它应该执行以下操作:
/** * Recieves the list of arguments and copies to conffile the name of * the configuration file. * Returns 1 if the default file name was used or 2 if * the parameter -f existed and therefor the specified name was used. Returns 0 if there is a -f * parameter but is invalid. (last argument)
*/
程序基本上会“询问”这两个选项之一:
1- Controller -f FCFS|LOOK
2- Controller FCFS|LOOK
如果是第二个,我们进入使用默认名称的情况。
int get_conf_name(char* argv[], char* conffile) {
// Searches for -f
s = strstr(*argv, "-f");
if(s != NULL){
if(//its valid){
strcpy(conffile, //the name of the file which comes after -f
return 2
}
else return 0
}
else{
strcpy(confile, "config.vss")
return 1
}
}
这里的问题是如何获取-f 后的单词并将其复制到配置文件中?而且,我可以像访问 conffile 一样访问 argv 吗,因为其中一个是数组? 我想到了使用 for 循环和 strlen,但这对计算机来说会是很多不必要的工作,不是吗?
最佳答案
我认为作业希望您逐一检查各个参数,并将它们与 "-f"
进行比较。
- 如果没有看到
-f
,就知道需要使用默认文件 - 如果你看到最后位置的标志,你就知道
-f
是无效的 - 如果你在位置
k
看到标志,那么文件名将在argv[k+1]
你的程序的框架应该是这样的:
bool foundFlag = false;
for (int i = 1 ; i < argc ; i++) {
if (strcmp(argv[i], "-f") == 0) {
if (i == argc-1) {
// Error
} else {
// argv[i+1] is the file name;
}
foundFlag = true;
break;
}
}
if (!foundFlag) {
// Default name is used
}
关于c - 指针和字符串操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19620557/