创建一个文件描述符 [英] Create a file descriptor

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

问题描述

我想在C中创建一个文件描述符,其值我将在代码中指定. 我有一个整数变量,它指定要创建的文件描述符的值.例如,我可能需要一个值为5的文件描述符,然后将该文件描述符与名为"sample.dat"的文件相关联.

I want to create a file descriptor in C whose value i will specify in code. I have a integer variable which specifies the value of file descriptor to be created. For example i may need a file descriptor whose value is 5 and later associate that with the file named "sample.dat" .

推荐答案

fd = open ("sample.dat", O_RDONLY);打开文件

dup2 (fd, 5);并将文件描述符fd复制到描述符编号5

dup2 (fd, 5); and copy the file descriptor fd into the descriptor number 5

现在您可以执行read (5, buffer, BUFF_MAX);或也可以使用fd访问相同的文件.如果不需要,您需要显式关闭fd.

now you can do read (5, buffer, BUFF_MAX); or also use fd to access the same file. You need to close the fd explicitly if you do not need it.

如@Arkadiy所述,请参阅man dup2了解详情.

As @Arkadiy told see man dup2 for details.

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

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