
緩衝式 I/O
|
85
fputc()
的用法很簡單:
if (fputc ('p', stream) == EOF)
/* 錯誤 */
此例會把字符
p
寫入
stream
(此串流必須被開啟以備寫入)。
寫入一個字串
函式
fputs()
可用於把一整個字串寫入所指定的串流:
#include <stdio.h>
int fputs (const char *str, FILE *stream);
fputs()
會把引數
str
所指向之「以 null 終止的」(null- terminated)字串全都寫入引數
stream
所指向的串流。執行成功時,
fputs()
會傳回一個非負值;執行失敗時,則傳回
EOF
。
下面的例子會以附加模式開啟檔案以備寫入,接著把所指定的字串寫入與檔案相對應的
串流,然後開閉串流:
FILE *stream;
stream = fopen ("journal.txt", "a");
if (!stream)
/* 錯誤 */
if (fputs ("The ship is made of wood.\n", stream) == EOF)
/* 錯誤 */
if (fclose (stream) == EOF)
/* 錯誤 */
寫入二元資料
當程式需要寫入複雜的資料結構時,使用個別的字符以及輸入列是無法妥善處理的。欲
直接儲存二元資料,例如 C 的變數,可以使用標準 I/O 程式庫所提供的
fwrite()
:
#include <stdio.h>
size_t fwrite (void *buf,
size_t ...