micheal b micheal b - 6 months ago 12
Linux Question

Getting weird output reading from stdin

So what i'm trying to do is repeat the input from keyboard to stdout. It must use read/write

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define BUFFSIZE 1024
int main() {
char buffer[BUFFSIZE];
while (1)
if (read(0, buffer, sizeof(buffer)))
write(1, buffer, sizeof(buffer));
return 0;
}


If I type "hello" it creates a new line with a bunch of weird symbols & letters and on another new line it will say "hello"

Answer

You should, save the return value of read() and write only that ammount which is what read().

Your code is also too confusing and doesn't make a lot of sense, your while loop should have a condition and there is inhertently one in such a program,

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define BUFFSIZE 1024
int  
main(void) 
{
    char buffer[BUFFSIZE];
    ssize_t length;
    while ((length = read(STDIN_FILENO, buffer,  sizeof(buffer))) > 0)
        write(STDOUT_FILENO, buffer, length); 
    return 0;
}
Comments