c - 指针和字符串操作

标签 c string pointers

我正在用 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/

相关文章:

永远不会执行的代码可以调用未定义的行为吗?

将十进制值转换为十六进制值

c++ - 将未签名的char Buffer拆分并存储到结构中

c - 如何提取 GTK 程序的菜单栏

无法从 C 中的结构打印字符串

JavaScript:字符串提取

c++ - 如何在 C++11 中将 unix 时间戳字符串正确转换为 time_t?

c - 使用 C++11 智能指针作为 C 函数参数

c - 在 C 中使用结构和指针时出现段错误

c - 危险指针: get the local pointer