You are failing to take account of the return value from read(), where it tells you how many bytes were read. On the last read(), and possibly other times, that will be fewer than would fit in buf. You always write the whole of buf, so when fewer bytes were read, you write spurious stuff.
You should use the version of write() that takes a start and length value.
While I'm here, though, your code will be slow. A buffer of 48 bytes is much too small; a few thousand bytes would be more typical. Also, you should not flush() after every write. If you flush() at all, do it only after writing everything. In fact, close() will generally do an implicit flush() anyway.