C語言的檔案IO函式

2021-10-07 12:50:59 字數 2108 閱讀 9670

c語言檔案i/o函式主要指fprintf()、fscanf()、fgets()和fputs()。它們既可以實現向gets()、puts()、getc()和putc()函式樣從鍵盤和螢幕進行輸入輸出,也可以對檔案進行輸入輸出。

標頭檔案:#include

定義函式:int fprintf(file * stream, const char * format, ...);

函式說明:fprintf()會根據引數format 字串來轉換並格式化資料, 然後將結果輸出到引數stream 指定的檔案中, 直到出現字串結束(』\0』)為止。

示例:

/* addaword.c -- uses fprintf(), fscanf(), and rewind() */

#include

#include

#include

#define max 41

intmain

(void

)puts

("enter words to add to the file; press the #");

puts

("key at the beginning of a line to terminate.");

while((

fscanf

(stdin

,"%40s"

, words)==1

)&&(words[0]

!='#'))

fprintf

(fp,

"%s\n"

, words)

;puts

("file contents:");

rewind

(fp)

;/* go back to beginning of file */

while

(fscanf

(fp,

"%s"

,words)==1

)puts

(words)

;puts

("done!");

if(fclose

(fp)!=0

)fprintf

(stderr

,"error closing file\n");

return0;

}

該程式可以在檔案中新增單詞。使用"a+"模式,程式可以對檔案進行讀寫操作。首次使用該程式,它將建立wordy檔案,以便把單詞存入其中。隨後再使用該程式,可以在wordy檔案後面新增單詞。雖然"a+"模式只允許在檔案末尾新增內容,但是該檔案模式可以讀整個檔案。rewind()函式讓程式回到檔案開始處,方便while迴圈列印整個檔案的內容。注意,rewind()接受乙個檔案指標作為引數。

下面是在cygwin在windows下模擬的linux環境下執行示例(可執行程式名字為a.exe):

$ ./a.exe[第一次執行]

enter words to add to the file; press the #

key at the beginning of a line to terminate.

the fabulous programmer

#file contents:

thefabulous

programmer

done!

$ ./a.exe[第二次執行]

enter words to add to the file; press the #

key at the beginning of a line to terminate.

enchanted the

large

#file contents:

thefabulous

programmer

enchanted

thelarge

done!

這兩個函式的分析可以參考前面的部落格《c語言的字串輸入fgets()函式》和《c語言的字串輸出fputs()函式》。

C 語言檔案I O相關函式

一 i o相關函式 函式描述 intopen const char path,int oflag,位於 標頭檔案 可以開啟或建立乙個檔案。引數見下方1 返回值 若成功,返回檔案描述符 若出錯,返回 1。intopenat int fd,const char path,int oflag,位於 標頭檔...

C語言 檔案IO

c語言 檔案io include stdafx.h include include include using namespace std 使用標頭檔案的命名空間 struct student struct student stu 10 初始化結構體的大小為10 初始化結構體 void initst...

C的檔案IO函式

經常遇到在看各種書籍的時候對io類的各種描述在這裡希望總結一下,留到下次進行閱讀 file f fclose f 關閉檔案流f fopen fname,mode fopen s fname mode,file 開啟乙個檔案流 file freopen const char path,const ch...