文件描述符和文件指针的区别

文件描述符是一个内核级的整形数值,用来表示一个打开的文件。由 open()、creat()、dup()、pipe() 等系统调用获得,由 read()、write() 等系统调用使用。文件描述符不带缓存功能,在可移植性和读写效率方面存在一定的问题。

文件指针是一个C标准库的结构体指针(FILE *),用来表示一个文件,由 fopen() 等系统调用获得,由 fread()、fwrite() 等系统调用使用。文件指针封装了文件描述符,是一个更高级别的接口,具有缓存功能,以及错误标示和 EOF 检查等功能,具有更好的可移植性和读写效率。

fileno() 可以从文件指针得到文件描述符。fdopen() 可以从文件描述符得到文件指针。
示例代码:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

void test(void) {
    char *str = "hello, world";
    char buf[128];

    int fd = open("a.txt", O_RDWR);
    printf("fd from open: %d\n", fd);

    write(fd, str, strlen(str) + 1);
    printf("write %s by fd\n", str);

    FILE *fp = fdopen(fd, "rw");
    rewind(fp);

    int ret = fread(buf, 1, 128, fp);
    printf("read %s by fp, result: %d\n", buf, ret);

    int fd2 = fileno(fp);
    printf("fd from fileno: %d\n", fd2);

    close(fd);
}

int main(void) {
    test();

    return 0;
}

运行结果:

$ ./main
fd from open: 3
write hello, world by fd
read hello, world by fp, result: 13
fd from fileno: 3

猜你喜欢

转载自blog.csdn.net/choumin/article/details/111664809
今日推荐