解釋 C 語言中的 fgetc() 和 fputc() 函式
檔案是記錄的集合,或者說是硬碟上的一個位置,用於永久儲存資料。
檔案操作
在C 程式語言中,檔案操作如下:
- 命名檔案
- 開啟檔案
- 從檔案讀取
- 寫入檔案
- 關閉檔案
語法
開啟檔案的語法如下:
FILE *File pointer;
例如,FILE * fptr;
命名檔案的語法如下:
File pointer = fopen ("File name", "mode");
例如,
fptr = fopen ("sample.txt", "r"); FILE *fp; fp = fopen ("sample.txt", "w");
fgets( ) 和 fputs( ) 函式
fgets() 用於從檔案讀取字串。
fgets() 函式的語法如下:
fgets (string variable, No. of characters, File pointer);
例如,
FILE *fp; char str [30]; fgets (str,30,fp);
fputs() 函式 用於將字串寫入檔案。
fputs() 函式的語法如下:
fputs (string variable, file pointer);
例如,
FILE *fp; char str[30]; fputs (str,fp);
使用 fgets() 和 fputs() 函式的 C 程式
#include <stdio.h> int main() { FILE *fptr = fopen("sample.txt", "w"); fputs("TutorialPoints
", fptr); fputs("C programming
", fptr); fputs("Question & Answers", fptr); fclose(fptr); fptr = fopen("sample.txt", "r"); char string[30]; while (fgets(string, 30, fptr) != NULL) { printf("%s", string); } fclose(fptr); return 0; }
輸出
執行上述程式時,會產生以下結果:
TutorialPoints C programming Question & Answers
廣告