J. Doe
J. Doe

Reputation: 101

read ( C function ) behave strangely

Let consider a fragment of code:

char *buffer = (char*) malloc(MAX_LENGTH_OF_COMMAND);
while(1){
    printf("gsh> ");

    read(0, buffer, sizeof(buffer) );

}

And behaviour is quite strange. I mean, the output for following input "input,input,input" is "gsh> gsh> gsh> gsh>".

So I expected that there is a interrupt during I/O process ( I mean getting data from user) because waiting for user is a wasting of time. Ok, I understand it. But, what if I have to use buffer in next line, for example:

char *buffer = (char*) malloc(MAX_LENGTH_OF_COMMAND);
while(1){
    printf("gsh> ");

    read(0, buffer, sizeof(buffer) );
    // do something with buffer.
}

So it is necessary to have COMPLETE buffer ( input). I don't understand that and I don't know what is way to ensure that complete input is available.

Please explain. ( and correct my train of thought).

Thanks in advance.

Upvotes: 0

Views: 73

Answers (1)

Joshua
Joshua

Reputation: 43188

You just discovered that read() doesn't guarantee how many bytes it will read. You normally have to call read() in a loop until you find input delimiting characters (such as a newline). In addition, we note that after said newline, you will need to keep whatever remains in the read buffer (if anything) as it is valid input to the next thing that needs to read().

Please note that read()'s return is the number of bytes it read, and your input will not be null-terminated (because it's not expecting a string).

Upvotes: 4

Related Questions