fopen/freopen/fdopen

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.This
function is often used with descriptors that are returned by the functions that
create pipes and network communication channels. Because these special types
of files cannot be opened with the standard I/O fopen function, we have to call
the device-specific function to obtain a file descriptor, and then associate this
descriptor 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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章