Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C中的stdin上使用fgets()而不是fscanf()?_C_Unix_Stdin_Fgets - Fatal编程技术网

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

如何在C中的stdin上使用fgets()而不是fscanf()?,c,unix,stdin,fgets,C,Unix,Stdin,Fgets,我想使用fgets而不是fscanf来获取stdin并通过管道将其发送给子进程。下面的代码用于对文件中的行进行排序,但替换 fscanf(stdin, "%s", word) 与 给我一个警告 warning: comparison between pointer and integer [enabled by default] 否则,该计划似乎有效。知道我为什么会收到警告吗 int main(int argc, char *argv[]) { pid_t sortPid; int

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

fscanf(stdin, "%s", word)

给我一个警告

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
,fgets a
char*
。由于EOF是一个
int
,因此与EOF的比较会导致出现一个
char*
警告


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

fscanf返回一个
int
,fgets返回一个
char*
。由于EOF是一个
int
,因此与EOF的比较会导致出现一个
char*
警告

fgets在EOF或error时返回NULL,因此请检查该值。

的原型是:

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);
    }
}
其原型是:

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