2013-04-05 49 views
2

所以我的程序的特定部分看起來是這樣的:爲什麼閱讀不行,fgets在我的程序中工作正常?

printf("Please input command:\n>"); 
While 1 { 
    if ((int c = read(STDIN_FILENO, input, Buffer_size) == 0) { 
     break; 
    } 
    rest of the program uses strtok to break the input 
    down and store in array. Then pass it to a function which checks for 
    various commands and prints whatever was the command 
    suppose to do or gives syntax error for incorrect commands 

    printf(">"); //last line 

} 

所以這裏發生了什麼:

Please input command: 
addperson Batman 
>person added 
blahblah 
Error: incorrect syntax 

出於某種原因,它不打印「>」。每次我輸入任何東西之後,即使使用正確的命令,它也會說同樣的事情。

但是,如果我用這個:

printf("Please input command:\n>"); 
while 1 { 
    if (fgets(input, Buffer_size, stdin) == NULL) { 
     break; 
    } 
    ... 
    printf(">"); 

} 

我得到:

Please input command: 
> add_person Batman 
person added 
> blahbagwa 
Incorrect syntax 
> add_person Superman 
person added 

注意如何 「>」 出現在每個輸出?我不知道爲什麼閱讀不能正常工作;也許我對閱讀的理解不是很好。有人有什麼主意嗎?

回答

-1

read()會阻塞,直到它收到足夠的輸入來填充整個緩衝區,因爲fgets()將爲每個輸入的行返回一個緩衝區。

+0

你的意思是說,如果它沒有填充緩衝區,它不會繼續運行下一行? – shn 2013-04-05 01:29:00

+0

@shn您將在同一個緩衝區中獲得下一行,即它將包含所有輸入(甚至被截斷),直到緩衝區滿時爲止。 'read()'會像wait(block)一樣,直到緩衝區滿了。 – epatel 2013-04-05 01:32:11

+0

實際上可以避免這個問題嗎?我嘗試在讀取行之前執行bzero(輸入,Buffer_size)。仍然無法正常工作,因爲提供錯誤的語法會導致打印問題。 – shn 2013-04-05 01:38:03