2024年3月30日发(作者:)

fopen(打开文件)

相关函数 open,fclose

表头文件 #include

定义函数 FILE * fopen(const char * path,const char * mode);

函数说明 参数path字符串包含欲打开的文件路径及文件名,参数mode字符串则

代表着流形态。

mode有下列几种形态字符串:

r 打开只读文件,该文件必须存在。

r+ 打开可读写的文件,该文件必须存在。

w 打开只写文件,若文件存在则文件长度清为0,即该文件内容会消失。若文件不存

在则建立该文件。

w+ 打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件

不存在则建立该文件。

a 以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写

入的数据会被加到文件尾,即文件原先的内容会被保留。

a+ 以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存

在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。

复制代码 代码如下:

r Open text file for reading. The stream is positioned at the beginnin

g of the file.

r+ Open for reading and writing. The stream is positioned at the begi

nning of the file.

w Truncate file to zero length or create text file for writing. The strea

m is positioned at the beginning of the file.

w+ Open for reading and writing. The file is created if it does not exi

st, otherwise it is truncated. The stream is posi‐

tioned at the beginning of the file.

a Open for appending (writing at end of file). The file is created if i

t does not exist. The stream is positioned at the

end of the file.

a+ Open for reading and appending (writing at end of file). The file i

s created if it does not exist. The initial file posi‐