简体   繁体   中英

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

I want to use fgets instead of fscanf to get stdin and send it to a child process via a pipe. The code below works for sorting the lines in the file but replacing

fscanf(stdin, "%s", word)

with

fgets(word, 5000, stdin)

gives me the warning

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

Otherwise the program seems to work. Any ideas why I am getting the warning?

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 returns an int , fgets a char * . Your comparision with EOF results in the warning for a char * since EOF is an int .

fgets returns NULL on EOF or error, so check for that.

The prototype of fgets is:

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

fgets will read the newline character into your string,so if you use it, part of your code may write as:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM