
- 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 庫 - putc() 函式
C 庫的 putc() 函式將引數 char 指定的字元(一個無符號字元)寫入指定的流,並向前移動流的位置指示器。
語法
以下是 C 庫 putc() 函式的語法:
int putc(int char, FILE *stream);
引數
此函式接受以下引數:
-
char: 這是要寫入的字元。它作為 int 傳遞,但會在內部轉換為無符號字元。
-
stream: 這是指向 FILE 物件的指標,用於標識要寫入字元的流。該流可以是任何輸出流,例如以寫入模式開啟的檔案或標準輸出。
返回值
如果成功,putc() 函式會返回寫入的字元,作為轉換為 int 的無符號字元。如果發生錯誤,它將返回 EOF 並設定流的相應錯誤指示器。
示例 1
將字元寫入檔案
此示例以寫入模式開啟一個檔案,並將字元 'A' 寫入其中。
#include <stdio.h> int main() { FILE *file = fopen("example1.txt", "w"); if (file == NULL) { perror("Error opening file"); return 1; } putc('A', file); fclose(file); return 0; }
輸出
以上程式碼將建立一個名為 example1.txt 的檔案,並將字元 'A' 寫入其中。
A
示例 2
使用錯誤處理將字元寫入檔案
此示例透過檢查 putc() 的返回值並列印錯誤訊息(如果寫入失敗)來演示錯誤處理。
#include <stdio.h> int main() { FILE *file = fopen("example3.txt", "w"); if (file == NULL) { perror("Error opening file"); return 1; } if (putc('B', file) == EOF) { perror("Error writing to file"); fclose(file); return 1; } fclose(file); return 0; }
輸出
執行以上程式碼後,將建立一個名為 example3.txt 的檔案,並將字元 'B' 寫入其中。如果寫入過程中發生錯誤,將顯示錯誤訊息。
B
廣告