C語言fopen函式了解

2021-07-13 10:27:14 字數 2023 閱讀 3491

fopen()函式功能:open a file.

原型:file * fopen(const char * path,const char * mode);

需要#include

返回值:檔案順利開啟後,指向該流的檔案指標就會被返回。如果檔案開啟失敗則返回null,並把錯誤**存在errno 中。

一般開啟檔案會進行讀取或寫入操作,如果開啟檔案失敗,也就無法順利進行相應的讀寫操作,所以一般在呼叫fopen()之後要作錯誤判斷及處理。

引數path字串包含欲開啟的檔案路徑及檔名,引數mode字串則代表著流形態。

mode有以下幾種形態

"r"opens for reading. if the file does not exist or cannot be found, thefopen call fails.

"w"opens an empty file for writing. if the given file exists, its contents are destroyed.

"r+"opens for both reading and writing. (the file must exist.)

"w+"opens an empty file for both reading and writing. if the given file exists, its contents are destroyed."b"open in binary (untranslated) mode; translations involving carriage-return and linefeed characters are suppressed. 文字模式和二進位制模式的區別:1.在windows系統中,文字模式下,檔案以"\r\n"代表換行。若以文字模式開啟檔案,並用fputs等函式寫入換行符"\n"時,函式會自動在"\n"前面加上"\r"。即實際寫入檔案的是"\r\n" 。2.在類unix/linux系統中文字模式下,檔案以"\n"代表換行。所以linux系統中在文字模式和二進位制模式下並無區別。

demo示例1:

#include #include 

#include

intmain()

//getc()用於在開啟檔案中獲取乙個字元

while((ch=getc(fp))!=eof)

printf("\n

");

fclose(fp);

fp=null;

system(

"pause

");

return

0;

}

demo2:

#include file *stream,*stream2;  

int main(void

)

else

if ((stream2=fopen("

data2.txt

","w+

"))==null)

else

if(stream)

} numclosed =_fcloseall();

printf(

"number of files close by _fcloseall %u\n

",numclosed);

system(

"pause

");

return

0;

}

檔案操作時需要注意以下幾點:  1、在定義檔案指標時,要將檔案指標指向空;如 file *fp = null;

2、檔案操作完成後,需要將檔案關閉,一定要注意,否則會造成檔案所占用記憶體洩露和在下次訪問檔案時出現問題。

3、檔案關閉後,需要將檔案指標指向空,這樣做會防止出現游離指標,而對整個工程造成不必要的麻煩;如:fp = null;

【from msdn && 百科】

C語言fwrite函式了解

fwrite 函式 write data to a stream 原型 size t fwrite const void buffer,size t size,size t count,file stream 注意 這個函式以二進位制形式對檔案進行操作,不侷限於文字檔案 demo cpp view ...

c語言fopen函式

c語言函式fopen 函式簡介 1.函式功能 開啟乙個檔案 2.函式原型 file fopen const char path,const char mode 3.相關函式 open,fclose,fopen s 1 wfopen 所需庫 4.返回值 檔案順利開啟後,指向該流的檔案指標就會被返回。如...

C語言函式fopen

函式功能 開啟乙個檔案 函式原型 file fopen const char path,const char mode open,fclose,fopen s 引 wfopen 所需庫 stdio.h 返回值 檔案順利開啟後,指向該流的檔案指標就會被返回。如果檔案開啟失敗則返回null,並把錯誤 存...