Last Updated on 2021-04-29 by Clay
不論是在什麼程式語言當中,關於文字的處理都是重要的。畢竟在電腦系統當中,有許多的設定都是直接透過文字來進行操作。
故本節筆記則主要紀錄如何輸入、輸出文字,同時記述而和讀檔寫檔。
getchar()putchar()fopen()fwrite()
getchar() 與 putchar()
使用 getchar() 可以取得使用者輸入鍵盤的字元。在使用者按下 Enter 鍵之後,字元會儲存於緩衝區當中,等待 putchar() 讀取。
值得注意的是,putchar() 一次只從緩衝區中取得一個字元、scanf() 則是可以接收多個類型的資料。
#include <stdio.h> int main() { char c; c = getchar(); while (c != EOF) { putchar(c); c = getchar(); } return 0; }
Ouptut:
Today
Today
is
is
a
a
nice
nice
day
day
^C
可以看到,不管我們輸入了什麼,終端機都會打印出一模一樣的字串。最後我使用了 Ctrl+C 終止程式。
使用 fopen() 讀檔
假設我們在當前目錄底下有份檔案 file.txt,內容為:
Today is a nice day.
I want to go to play.
那麼我們可以使用 fopen() 讀取這份檔案。
#include <stdio.h> int main() { FILE *fp = fopen("file.txt", "r"); char c; while ((c=getc(fp)) != EOF) { printf("%c", c); } fclose(fp); return 0; }
Ouptut:
Today is a nice day.
I want to go to play.
getchar() 通常為接受鍵盤輸入、getc() 通常為接受文件輸入。
使用 fwrite() 寫檔
#include <stdio.h> int main() { FILE *fp = fopen("file.txt", "w"); char c[] = {'H', 'e', 'l', 'l', 'o'}; fwrite(c, 1, sizeof(c), fp); fclose(fp); return 0; }
接著,在終端機中查看 file.txt 檔是否已經被新的內容覆蓋了。
cat file.txt
Output:
Hello
(Optional) 讀檔寫檔模式
| 模式 | 敘述 |
|---|---|
| r | 開啟檔案讀取文字資料 |
| w | 開啟檔案寫入資料。若檔案存在則覆蓋、不存在則建立 |
| a | 開啟檔案寫入資料。若檔案存在則接續寫入資料、不存在則建立 |
| rb | 開啟檔案讀取二進位元資料 |
| wb | 開啟二進位元檔案寫入資料。若檔案存在則覆蓋、不存在則建立 |
| ab | 開啟二進位元檔案寫入資料。若檔案存在則接續寫入資料、不存在則建立 |
| r+ | 以可讀寫方式開啟檔案 |
| w+ | 以可讀寫方式開啟檔案寫入資料。若檔案存在則覆蓋、不存在則建立 |
| a+ | 以可讀寫方式開啟檔案寫入資料。若檔案存在則接續寫入、不存在則建立 |
| rb+ | 以可讀寫方式開啟二進位元檔案。 |
| wb+ | 以可讀寫方式開啟二進位元檔案寫入資料。若檔案存在則覆蓋、不存在則建立 |
| ab+ | 以可讀寫方式開啟二進位元檔案寫入資料。若檔案存在則接續寫入、不存在則建立 |
References
- https://fresh2refresh.com/c-programming/c-file-handling/putchar-getchar-function-c/
- https://www.studytonight.com/c/c-input-output-function.php
- https://www.tutorialspoint.com/c_standard_library/c_function_fwrite.htm
- https://www.tutorialspoint.com/c_standard_library/c_function_fopen.htm