do-while循环执行1或2个循环太多

时间:2013-05-13 17:13:51

标签: c while-loop do-while

我有这个C函数,对我来说似乎是以两种方式随机行为: 1.只有在输入'menu'并且因此调用了user_cfg时,在返回现有文件的路径作为输入之后,while循环继续运行几次。 2.当代码出现在下面时,当输入现有文件的路径时,我遇到分段错误。据我所见,我没有改变代码,因为它在30分钟前正常工作(除了上述问题)。

char *user_cfg() {
   printf("\nProvide the path for the configuration file or enter \"menu\" to go back:\n");
   char escape[5] = {"menu"};
   char buf[101] = {0};
   char path_input[101] = {0};
   char *userSpecifiedFilepath;

   do {
     if (fgets (buf, sizeof(buf), stdin) != NULL)
       if (sscanf(buf, "%s", &path_input)) {
         userSpecifiedFilepath = path_input;
         if (*path_input == *escape)
           user_cfg();
       }
      } while (!file_exists(userSpecifiedFilepath));
   return userSpecifiedFilepath;
}

bool file_exists(const char *filename) {
  FILE *file;
  file = fopen(filename, "r");
  fclose(file);
  if (file != NULL) {
    return true;
  }
  return false;
}

2 个答案:

答案 0 :(得分:2)

您正在返回本地变量的地址。这是一个未定义的行为,可能是分段错误的原因。

解决此问题的简单方法(但不是正确的方法:p)将您的path_input声明为静态。

static char path_input[101] = {0};

在尝试运行代码之前修复警告可以帮助您避免这些基本问题。

如果userSpecifiedFilepath失败,fgets的价值是多少?

答案 1 :(得分:1)

文件中的

存在,if语句错误。文件将成为指针或NULL'\ 0',它不会评估您希望它的方式。你应该使file = to fopen,然后检查它是否为NULL。如果没有,返回true。