与Unix文件描述符相当的fgetc [英] Equivalent of fgetc with Unix file descriptors

查看:171
本文介绍了与Unix文件描述符相当的fgetc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

fgetc(3)函数将 FILE * 作为其输入流。我必须使用 read(2)重新实现一次性输入,或者是否有< unistd.h> -style相当于取一个整数文件描述符?

The fgetc(3) function takes a FILE * as its input stream. Must I reimplement character-at-a-time input with read(2), or is there a <unistd.h>-style equivalent taking an integer file descriptor instead?

推荐答案

不,没有这样的东西,请从不执行阅读(fd,& ch,sizeof(char))(以下说明)。

No, there isn't such a thing, and please never do read(fd, &ch, sizeof(char)) (explanations below).

函数 read(2)通常作为系统调用实现。操作系统内核。虽然这里不讨论这种事情的内部(和时髦)细节,但总的想法是系统调用(通常)便宜。

The function read(2) is usually implemented as a system call to the operating system kernel. Although the internal (and funky) details of such a thing shall not be discused here, the overall idea is that system calls are (usually) not something cheap.

对于用户空间应用程序和内核来说只是为了从文件描述符中获取单个字符而进行系统调用是低效的。

It would be inefficient for both the userspace application and the kernel to do a system call just to get a single character from a file descriptor.

例如, fgetc(3)通常最终会在 FILE 对象的结构中进行一些缓冲。这意味着来自 fgetc(3)的内部 read(2)不仅会读取单个字符,而是会尝试获取更多内容效率。

For instance, fgetc(3) usually ends up doing some buffering inside the structure of the FILE object. This means that the internal read(2) from fgetc(3) wouldn't just read a single character, but rather it'll try to get more for the sake of efficiency.

无论如何,搞乱这种低级别的东西通常不是一个好主意。通过使用 FILE 整体)的所有好处=nofollow> fdopen(3)从文件描述符创建 FILE 对象,因为您的问题似乎暗示您此刻只有一个原始文件描述符。

Anyway, it's not usually a good idea to mess up with such low-level stuff. You can get all the benefits of buffering (and of FILEs overall) by using fdopen(3) to create a FILE object from a file descriptor, as your question appears to imply that you have at hand just a raw file descriptor at the moment.

这篇关于与Unix文件描述符相当的fgetc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆