C- how to read input from stdin until newline character using read()? [closed]

Sometimes I don’t know what teachers are thinking. Instead of teaching how to
use the correct functions properly, they give you assignments where you cannot
use variables, or you cannot return pointers and you cannot even use
functions. For me it’s like when the master carpenter tells the young
apprentice nail this nail, but don’t use your hammer, use your screwdriver
. Enough about my rant…

The problem here is that you want to read content that has meaning (newline for
example) with a function that just reads a block of bytes and doesn’t care for
the meaning of the bytes. If the newline is in the middle of the block you’ve
read, then you’ve read too much. The best way would be to read one byte at a
time and check if it is the newline.

int get_from_user(char *buffer, size_t size)
    size_t cnt = 0;
    char c;

    if(buffer == NULL || size == 0)
        return 0;

    while(read(STDIN_FILENO, &c, 1) == 1 && cnt < size - 1)
        if(c == '\n')
            buffer[cnt] = 0;
            return 1;

        buffer[cnt++] = c;

    buffer[cnt] = 0; // making sure it's 0-terminated
    return 1;

And when you want to read:

char line[100];
get_from_user(line, sizeof line);

Browse More Popular Posts

Leave a Comment