
- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
C 庫 - freopen() 函式
C 庫函式 FILE *freopen(const char *filename, const char *mode, FILE *stream) 將一個新的檔名與給定的開啟流關聯,同時關閉流中的舊檔案。
語法
以下是 C 庫函式 freopen() 的語法:
FILE *freopen(const char *filename, const char *mode, FILE *stream);
引數
以下是 C 庫函式 freopen() 的括號內可以使用引數的列表:
- filename : 指向一個空終止字串的指標,指定要開啟的檔名。如果 filename 為 NULL,freopen 函式嘗試更改現有流的模式。
- mode : 指向一個空終止字串的指標,指定要開啟檔案的模式。此模式字串可以是:
- r : 以讀取方式開啟。
- w : 以寫入方式開啟(將檔案截斷為零長度)。
- a : 以追加方式開啟(寫入內容新增到檔案末尾)。
- r+ : 以讀寫方式開啟。
- w+ : 以讀寫方式開啟(將檔案截斷為零長度)。
- a+ : 以讀寫方式開啟(寫入內容新增到檔案末尾)。
- stream : 指向 FILE 物件的指標,指定要重新開啟的流。此流通常與檔案關聯,但也可能是標準輸入、輸出或錯誤流 (stdin、stdout 或 stderr)。
返回值
成功時,freopen 返回指向 FILE 物件的指標。失敗時,它返回 NULL 並設定全域性變數 errno 以指示錯誤。
示例 1:將標準輸出重定向到檔案
此示例將標準輸出 (stdout) 重定向到名為 output.txt 的檔案。
以下是 C 庫 freopen() 函式的示例:
#include <stdio.h> int main() { FILE *fp = freopen("output.txt", "w", stdout); if (fp == NULL) { perror("freopen"); return 1; } printf("This will be written to the file output.txt instead of standard output.\n"); fclose(fp); return 0; }
輸出
上述程式碼在 output.txt 檔案中生成以下結果:
This will be written to the file output.txt instead of standard output.
示例 2:將標準輸入重定向到檔案
此示例將標準輸入 (stdin) 重定向到從名為 input.txt 的檔案讀取,並將內容列印到標準輸出。
#include <stdio.h> int main() { FILE *fp = freopen("input.txt", "r", stdin); if (fp == NULL) { perror("freopen"); return 1; } char buffer[100]; while (fgets(buffer, sizeof(buffer), stdin) != NULL) { printf("%s", buffer); } fclose(fp); return 0; }
輸出
執行上述程式碼後,我們在終端得到以下結果,並且 input.txt 的內容保持不變:
Line 1: This is the first line. Line 2: This is the second line.
廣告