简体   繁体   English

read()和getc()有什么区别

[英]What's the difference between read() and getc()

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? 我知道标准I / O会自动缓冲,但是我已将buf传递给read() ,所以read()也在进行缓冲,对吗? And it seems that getc() read data char by char, how much data will the buffer have before sending all the data out? 似乎getc()逐个读取char数据,在将所有数据发送出去之前,缓冲区将拥有多少数据?

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. 首先,在许多系统上, read是较低级的函数,甚至可能是直接进入OS的系统调用。 The read function also isn't standard C or C++, it's part of eg POSIX . read功能也不是标准的C或C ++,它是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. 没有缓冲(可能不在OS /内核级别),并且“二进制”和“文本”数据之间没有区别。 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. 在POSIX系统上,其中read是系统调用,它可以用于读取所有类型的设备,而不仅仅是文件。

The getc function is a higher level function. getc函数是更高级别的函数。 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). 它通常使用缓冲的输入(因此有时会将输入读入缓冲区中,有时使用read ,并且getc函数从该缓冲区中获取其字符)。 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. 作为标准库的一部分,它也是C和C ++规范的一部分。 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. 另一个区别是read始终也是一个函数,而getc可能是预处理器宏。

Comparing read and getc doesn't really make much sense, more sense would be comparing read with fread . 比较readgetc并没有多大意义,将readfread进行比较更有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM