-3

I am having trouble reading from stdin constantly until CTRL+D is pressed. I have to use read() from unistd.h. I am trying to simulate the cat function. Is there a way to make my buffer (which I print with %s) to look neat without the unnecessary spaces from read(STDIN_FILENO, buf, 256)?

Daniel Hedberg
  • 5,677
  • 4
  • 36
  • 61
Alex
  • 389
  • 1
  • 2
  • 14
  • 3
    Without seeing the code it's difficult to know what to suggest. – suspectus Mar 19 '13 at 22:20
  • I'm not sure exactly what your problem is, since you've posted no code, no error messages, and no output (expected or actual), but here's a shot in the dark: The read function doesn't null terminate for you, so you should be doing: `int rd = read(STDIN_FILENO, buf, 255); buf[rd]=0x0;`, assuming buf is declared as `char buf[256]` – FrankieTheKneeMan Mar 19 '13 at 22:39

1 Answers1

3

I am trying to simulate the cat function.

Here is a start:

ssize_t nread, nwrite;

while ((nread = read(STDIN_FILENO, buf, sizeof buf)) > 0) {
    nwrite = write(STDOUT_FILENO, buf, nread);
    /* Error handling and partial writes left as exercise. */
}
cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • Thanks i already have this piece of code, the problem is the sizeof(buf).. And found a little mistake in my code i am using prinf for the buf after reading...... – Alex Mar 19 '13 at 22:25
  • 1
    @Alex What's the problem with the `sizeof` ? – cnicutar Mar 19 '13 at 22:25
  • Well sorry it is late and i didnt notice that i had a printf() before my code for read/write stdin/out and was causing some chaos ;D.. Anyways will post some code after i am done.. – Alex Mar 19 '13 at 22:39