曲径通幽论坛

标题: fdopen() -- 将流挂靠到已有的文件描述符上 [打印本页]

作者: beyes    时间: 2012-8-11 13:48
标题: fdopen() -- 将流挂靠到已有的文件描述符上
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.





欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2