Search code examples
ccygwinsystem-callsfgets

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


So the specific part of my program looks like this:

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

}

So here's what happens:

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

For some reason it doesn't print: ">". Also everytime I enter anything after that it says the same thing always even with right commands.

But if I use this:

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

}

I get:

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

Notice how ">" appears in each output? I don't really know why read isn't working properly; perhaps my understand of read isn't very good. Does anyone have any idea?


Solution

  • read() will block until it has received enough input to fill the entire buffer where as fgets() will return a buffer for each entered line.