【问题标题】:How to use fgets() instead of fscanf() on stdin in C?如何在 C 中的标准输入上使用 fgets() 而不是 fscanf()?
【发布时间】:2013-05-12 23:31:03
【问题描述】:

我想使用 fgets 而不是 fscanf 来获取标准输入并通过管道将其发送到子进程。下面的代码用于对文件中的行进行排序但替换

fscanf(stdin, "%s", word)

fgets(word, 5000, stdin)

给我警告

warning: comparison between pointer and integer [enabled by default]

否则程序似乎可以工作。任何想法为什么我会收到警告?

int main(int argc, char *argv[])
{
  pid_t sortPid;
  int status;
  FILE *writeToChild;
  char word[5000];
  int count = 1;

  int sortFds[2];
  pipe(sortFds);

  switch (sortPid = fork()) {
    case 0: //this is the child process
      close(sortFds[1]); //close the write end of the pipe
      dup(sortFds[0]);
      close(sortFds[0]);
      execl("/usr/bin/sort", "sort", (char *) 0);
      perror("execl of sort failed");
      exit(EXIT_FAILURE);
    case -1: //failure to fork case
      perror("Could not create child");
      exit(EXIT_FAILURE);
    default: //this is the parent process
      close(sortFds[0]); //close the read end of the pipe
      writeToChild = fdopen(sortFds[1], "w");
      break;
  }

  if (writeToChild != 0) { //do this if you are the parent
    while (fscanf(stdin, "%s", word) != EOF) {
      fprintf(writeToChild, "%s %d\n",  word, count);
    }   
  }  

  fclose(writeToChild);

  wait(&status);

  return 0;
}

【问题讨论】:

    标签: c unix stdin fgets


    【解决方案1】:

    fscanf 返回一个int,f 得到一个char *。您与 EOF 的比较会导致 char * 的警告,因为 EOF 是 int

    fgets 在 EOF 或错误时返回 NULL,因此请检查。

    【讨论】:

      【解决方案2】:

      fgets的原型是:

      char * fgets(char * str, int num, FILE * stream);

      fgets 会将换行符读入你的字符串,所以如果你使用它,你的部分代码可能会写成:

      if (writeToChild != 0){
          while (fgets(word, sizeof(word), stdin) != NULL){
              count = strlen(word);
              word[--count] = '\0'; //discard the newline character 
              fprintf(writeToChild, "%s %d\n",  word, count);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多