Search code examples
ciobuffer

Read in while loop


I've been trying to wrap my head around buffers and the I/O functions that rely on them, when I came across this snippet of code, that at first seemed intuitive, but once I started playing with it, the results I got were unexpected.

I used a while loop to read() each line from the standard input and printf() to print out what I read. After a few inputs, the print outs started to get weird, which seemed off, knowing that read() overwrites the destination buffer each time it's called.

char line[256];
int n;

while((n = read(STDIN_FILENO, line, 256) > 0)
    printf("%s", line);

On the third take (abcdefghj) it seems printf started mixing results.

abc
abc
abcdef
abcdef
abcdefghj
cdeabcdefghj

Solution

  • read doesn't add a '\0' terminator to the end of the string - you need to do this yourself, e.g.

    while((count = read(STDIN_FILENO, line, 255) > 0)
    {                                    // ^^^ NB: need to allow room for terminator !
        line[count] = '\0';
        printf("%s", line);
    }
    

    Or alternatively you can tell printf how many chars to print and not worry about the terminator:

    while((count = read(STDIN_FILENO, line, 256) > 0)
    {                                    
        printf("%.*s\n", count, s);
    }