Equivalent of fgetc with Unix file descriptors

心已入冬 提交于 2019-12-25 04:43:37

问题


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?


回答1:


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

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.

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.

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.




回答2:


If you want to, you can open a file using open() -

int fh = open("abc.txt", O_RDONLY, S_IREAD);  // there are different permissions you can provide (refer to link).

and then you can use fh in read() calls.



来源:https://stackoverflow.com/questions/32131873/equivalent-of-fgetc-with-unix-file-descriptors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!