2013-05-12 62 views
0

我想使用fgets而不是fscanf來獲取stdin並通過管道將其發送給子進程。下面的代碼工作排序的文件中的行但如何使用fgets()而不是fscanf()在標準輸入C中?

fgets(word, 5000, 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; 
} 

回答

3

的fscanf返回int,FGETS一個char *。由於EOF爲int,因此與EOF的比較會導致char *的警告。

fgets在EOF或錯誤上返回NULL,所以檢查一下。

1

fgets原型爲:

字符*與fgets(字符* STR,INT NUM,FILE *流);

與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); 
    } 
} 
相關問題