fopen/freopen/fdopen

来源:互联网 发布:可靠性分析软件有哪些 编辑:程序博客网 时间:2024/05/20 19:28

fopen是用得比较多的,通常是打开文件读写。另外两个用得不多,但在系统编程时会用到。

freopen

通常与stdin,stdout,stderr一起用,有点重定向的味道

FILE *freopen(const char *restrict pathname, const char *restrict type,FILE *restrict fp);
  • 例1
 94     int a;                                                                                                               95            96     freopen("in.txt", "r", stdin); 97     while (scanf("%d", &a) != EOF) 98         printf("%d\n", a); 99           103     return 0;  

从in.txt中读,重定向到stdin,所以下面scanf从stdin接收data内容。

  • 例2
 94     int a;                                                                                                               95           100     freopen("in.txt", "w", stdout);101     for (a = 0; a<6; a++)102         printf("%d\n", a);103     return 0;    

这个例子正好与上面向抬,把stdout重定向到in.txt,所以printf输出的内容就不会在console显示,而被写到in.txt中去了。

fdopen

takes an existing file descriptor,which we could obtain from the open,dup,dup2,fcntl,pipe,socket,socketpair,or accept functions and associates a standard I/O stream with the descriptior.Thisfunction is often used with descriptors that are returned by the functions thatcreate pipes and network communication channels. Because these special typesof files cannot be opened with the standard I/O fopen function, we have to callthe device-specific function to obtain a file descriptor, and then associate thisdescriptor with a standard I/O stream using fdopen.
#include <stdio.h>FILE * fdopen(int fildes, const char * mode);

将文件描述符转成对应的句柄(指向文件的指针),比如下面是将标准输入stdin转为文件指针,会在console上输出hello!

106     FILE *fp = fdopen(0, "w+");107     fprintf(fp, "%s\n", "hello!");108     fclose(fp);