簡體   English   中英

如何在C中的stdin上使用fgets()而不是fscanf()?

[英]How to use fgets() instead of fscanf() on stdin in C?

我想使用fgets而不是fscanf來獲取stdin並將其通過管道發送給子進程。 下面的代碼用於對文件中的行進行排序,但是替換

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;
}

fscanf返回一個int ,fget一個char * 您與EOF的比較會導致警告為char *因為EOF是int

fgets在EOF或錯誤時返回NULL,因此進行檢查。

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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM