曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 3875|回复: 0
打印 上一主题 下一主题

[文件I/O] fdopen() -- 将流挂靠到已有的文件描述符上

[复制链接]

4917

主题

5879

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34382
跳转到指定楼层
楼主
发表于 2012-8-11 13:48:55 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
fdopen() 函数声明如下:
[C++] 纯文本查看 复制代码
#include <stdio.h>
FILE *fdopen(int fd, const char *mode);

该函数的作用是将一个流挂靠到已有的文件描述符上,这个已建立的文件描述符由 fd 来指定,挂靠的流由函数的返回给出;此外函数的第 2 个参数 mode 和fopen()  函数的一样。

测试代码:
[C++] 纯文本查看 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>

int main(void)
{
    long length;
    int fh;
    char buffer[20];
    FILE *fp;

    printf ("\nCreating samle.dat.\n");
    if ((fp = fopen("sample.dat", "w")) == NULL) {
      perror ("File was not create: ");
      exit (EXIT_FAILURE);
    }
    
    fputs ("Sample Program", fp);
    fclose (fp);

    memset (buffer, '\0', 20);

    if (-1 == (fh = open("sample.dat", O_RDWR | O_APPEND))) {
       perror ("Unable to open sample.data");
       exit (EXIT_FAILURE);
    }

    if (NULL == (fp = fdopen(fh, "r"))) {
       perror ("fdopen failed");
       close(fh);
       exit (EXIT_FAILURE);
    }
    
    if (14 != fread(buffer, 1, 14, fp)) {
       perror ("fread failed");
       fclose (fp);
       exit (EXIT_FAILURE);
    }
    
    printf ("Successfully read from the stream the following:\n%s. \n", buffer);
    fclose(fp);
    return 1;
}

运行输出:
[beyes@beyes   file]$ ./fdopen

Creating samle.dat.
Successfully read from the stream the following:
Sample Program.
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2024-5-3 07:43 , Processed in 0.168050 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表