putc 和 ungetc 和有什么区别?
int ungetc(int c, FILE *fp)
将字符 c 推回 fp,并返回 c 或 EOF
(如果出现错误)。
其中 int putc(int c, FILE *fp)
将字符 c 写入文件 fp 并返回写入的字符,或 EOF
表示错误。
//这些是 K&R 的声明。我发现自己很困惑,因为 putc()
可以在 getc
之后使用,并且可以作为 ungetc
工作。那么专门定义ungetc()有什么用呢。
int ungetc(int c, FILE *fp)
pushes the character c back into fp, and returns either c, or EOF
for an error.
where as int putc(int c, FILE *fp)
writes the character c into the file fp and returns the character written, or EOF
for an error.
//These are the statements from K&R. I find myself confused, because putc()
can be used after getc
and can work as ungetc
. So whats the use in specifically defining ungetc()
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
putc
向输出写入一些内容,因此它会出现在屏幕上或您将输出重定向到的文件中。ungetc
将某些内容放回到输入缓冲区中,因此下次调用getc
(或fgetc
等)时)这就是你会得到的。您通常使用 putc 来写入输出。当您读取输入时,您通常会使用 ungetc ,并且您知道已到达某些内容末尾的唯一方法是当您读取一个不能属于当前“某些内容”的字符时。例如,您正在读取并转换一个整数,您将继续,直到读取到数字以外的内容为止 - 然后您将该非数字字符作为来自流的下一个字符进行处理。
putc
writes something to output, so it appears on the screen or in the file to which you've redirected output.ungetc
put something back into the input buffer, so the next time you callgetc
(orfgetc
, etc.) that's what you'll get.You normally use
putc
to write output. You normally useungetc
when you're reading input, and the only way you know you've reached the end of something is when you read a character that can't be part of the current "something". E.g., you're reading and converting an integer, you continue until you read something other than a digit -- then youungetc
that non-digit character to be processed as the next something coming from the stream.ungetc 适用于打开供读取的流,并且不会修改原始文件。 putc 适用于为写入而打开的流,并将字节实际写入文件。
ungetc works with streams opened for read and doesn't modify the original file. putc works on streams opened for write and actually writes the byte to the file.
如果您对流
fp
执行ungetc
,然后再次执行getc
,您将返回刚刚输入的相同字符。如果你执行putc
“流继续移动”,随后的getc
将得到它后面的任何内容,如果有的话......getc
和ungetc
用于“向前查看”并在处理字符时出现某些特殊情况时将其放回,例如If you do
ungetc
on a streamfp
, and then you do agetc
again, you get back the same character you just put in. If you doputc
the "stream moves on", and a subsequentgetc
will get whatever is after it, if there is anything...The
getc
andungetc
are used to "peek ahead" and put it back if there is some special case in handling characters e.g.