I have two code segments:
while((n=read(0,buf,BUFFSIZE))>0)
if(write(1,buf,n)!=n)
err_sys("write error");
while((c=getc(stdin))!=EOF)
if(putc(c,stdout)==EOF)
err_sys("write error");
Some sayings on internet make me confused. I know that standard I/O does buffering automatically, but I have passed a buf to read()
, so read()
is also doing buffering, right? And it seems that getc()
read data char by char, how much data will the buffer have before sending all the data out?
Thanks
While both functions can be used to read from a file, they are very different. First of all on many systems read
is a lower-level function, and may even be a system call directly into the OS. The read
function also isn't standard C or C++, it's part of eg POSIX . It also can read arbitrarily sized blocks, not only one byte at a time. There's no buffering (except maybe at the OS/kernel level), and it doesn't differ between "binary" and "text" data. And on POSIX systems, where read
is a system call, it can be used to read from all kind of devices and not only files.
The getc
function is a higher level function. It usually uses buffered input (so input is read in blocks into a buffer, sometimes by using read
, and the getc
function gets its characters from that buffer). It also only returns a single characters at a time. It's also part of the C and C++ specifications as part of the standard library. Also, there may be conversions of the data read and the data returned by the function, depending on if the file was opened in text or binary mode.
Another difference is that read
is also always a function, while getc
might be a preprocessor macro.
Comparing read
and getc
doesn't really make much sense, more sense would be comparing read
with fread
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.