
- 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 庫 - fputc() 函式
C 庫函式 fputc(int char, FILE *stream) 將引數 char 指定的字元(一個無符號 char)寫入指定的流,並推進流的位置指示器。此函式是標準 I/O 庫的一部分,在處理 C 程式設計中的檔案操作時常用。
語法
以下是 C 庫函式 fputc() 的語法:
int fputc(int char, FILE *stream);
引數
此函式接受以下引數:
- int char: 要寫入的字元。雖然它是 int 型別,但它表示將無符號 char 轉換為 int 值。
- *FILE stream: 指向 FILE 物件的指標,標識輸出流。此流通常使用 fopen 等函式建立。
返回值
成功時,fputc 返回寫入的字元(無符號 char 轉換為 int)。失敗時,它返回 EOF(檔案結尾),並在流上設定相應的錯誤指示器。
示例 1:將單個字元寫入檔案
此程式以寫入模式開啟名為“example1.txt”的檔案,並將字元“A”寫入其中。
以下是 C 庫 fputc() 函式的示例。
#include <stdio.h> int main() { FILE *file = fopen("example1.txt", "w"); if (file == NULL) { perror("Failed to open file"); return 1; } fputc('A', file); fclose(file); return 0; }
輸出
執行上述程式碼後,檔案“example1.txt”將包含單個字元“A”。
示例 2:寫入多個字元
此程式將在當前目錄中建立一個名為 file.txt 的檔案,其中將包含 ASCII 值從 33 到 100 的字元。
#include <stdio.h> int main () { FILE *fp; int ch; fp = fopen("file.txt", "w+"); for( ch = 33 ; ch <= 100; ch++ ) { fputc(ch, fp); } fclose(fp); return(0); }
輸出
上述程式碼產生以下結果:
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd
廣告