繁体   English   中英

为什么读取不起作用而fgets在我的程序中可以正常工作?

[英]Why does read not work yet fgets work fine in my program?

因此,程序的特定部分如下所示:

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

注意在每个输出中如何显示“>”? 我真的不知道为什么阅读不能正常工作。 也许我对阅读的理解不是很好。 有人有什么主意吗?

read()将阻塞,直到它收到足够的输入以填满整个缓冲区为止,而fgets()将为每个输入的行返回一个缓冲区。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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