gabriel rosenkoetter on Wed, 28 Nov 2001 00:40:21 +0100 |
On Tue, Nov 27, 2001 at 04:18:21PM -0500, Bill Jonas wrote: > K&R 2nd Ed. has a simplistic cp program. It's basically just a while > loop using getchar and putchar. ("while ((c = getchar()) != EOF)"...) > Of course, it would be much more efficient to use read(2)/write(2) or > fread(3)/fwrite(3); the latter are in stdio.h and the former are in > unistd.h. The major difference that I can see is that the former uses > file descriptors while the latter uses (FILE *) structures. BTW, is > that the only real difference between them, or is there an advantage to > one set over the other? The big plus for read(2) and write(2) are that they work not just to files but also to sockets, named pipes, and so forth through the same interface. What's more, I do think they're more efficient, privided they're written with at least a little bit of sanity. At the least, they're sycalls (they have to be, they're accessing a vfs and, most likely, a physical device), which means that the kernel can manhandle the memory in order to do the read or write operation. I just did about as much digging as I really want to in both the Linux and the NetBSD source for sys_read() and sys_write() (have a look at src/linux/fs/read_write.c, for the curious), but didn't take long enough to figure out exactly how either is doing the actual reading and writing. (NetBSD has all of this purposely hidden behind both machine- and bus-independent code and macros, and I'm unfamiliar with this corner of the NetBSD kernel; Linux's sys_{read,write}() make calls to other read() and write() functions which I didn't take the time to track down.) I would suspect that this is kind of a file system- and hardware- dependent thing. That is, if your file system is willing to choke down a huge block and cache it for writing (and, if it presently has the space), or already has the stuff you want to read cached, then read(2) and write(2) of a larger-than-byte block will be ridiculously faster than doing it one character at a time, since the whole block can just be transferred right away. -- ~ g r @ eclipsed.net Attachment:
pgpHC63UROhRh.pgp
|
|