解釋C語言中檔案的putc()和getc()函式
一個檔案表示一系列位元組,無論它是文字檔案還是二進位制檔案。檔案是記錄的集合,或者說是硬碟上永久儲存資料的地方。
檔案操作
在C程式語言中,檔案操作如下:
- 命名檔案
- 開啟檔案
- 從檔案讀取
- 寫入檔案
- 關閉檔案
語法
開啟檔案的語法如下:
FILE *File pointer;
例如,FILE * fptr;
命名檔案的語法如下:
File pointer = fopen ("File name", "mode");
例如:
fptr = fopen ("sample.txt", "r"); FILE *fp; fp = fopen ("sample.txt", "w");
putc() 和 getc() 函式
putc() 函式用於將字元寫入檔案。
putc() 函式的語法如下:
putc (char ch, FILE *fp);
例如:
FILE *fp; char ch; putc(ch, fp);
getc() 函式用於從檔案讀取字元。
getc() 函式的語法如下:
char getc (FILE *fp);
例如:
FILE *fp; char ch; ch = getc(fp);
使用 putc() 和 getc() 函式的 C 程式
以下是使用 putc() 和 getc() 函式的 C 程式:
#include<stdio.h> int main(){ char ch; FILE *fp; fp=fopen("std1.txt","w"); //opening file in write mode printf("enter the text.press cntrl Z:"); while((ch = getchar())!=EOF){ putc(ch,fp); // writing each character into the file } fclose(fp); fp=fopen("std1.txt","r"); printf("text on the file:"); while ((ch=getc(fp))!=EOF){ // reading each character from file putchar(ch); // displaying each character on to the screen } fclose(fp); return 0; }
輸出
執行上述程式後,將產生以下結果:
enter the text.press cntrl Z: Hi Welcome to TutorialsPoint Here I am Presenting Question and answers in C Programming Language ^Z text on the file: Hi Welcome to TutorialsPoint Here I am Presenting Question and answers in C Programming Language
廣告