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. |