fopen()中w 和w+等各个参数的区别
2017-03-29 15:31
169 查看
函数简介
函数功能: 打开一个文件函数原型:FILE * fopen(const char * path,const char * mode);
相关函数:open,fclose,fopen_s[1]
,_wfopen
所需库: <stdio.h>
返回值: 文件顺利打开后,指向该流的文件指针就会被返回。若果文件打开失败则返回NULL,并把错误代码存在errno 中。
一般而言,打开文件后会作一些文件读取或写入的动作,若打开文件失败,接下来的读写动作也无法顺利进行,所以在fopen()后请作错误判断及处理。
参数说明:
参数path字符串包含欲打开的文件路径及文件名,参数mode字符串则代表着流形态。
mode有下列几种形态字符串:
r 打开只读文件,该文件必须存在。
r+ 打开可读写的文件,该文件必须存在。
rb+ 读写打开一个二进制文件,只允许读写数据。
rt+ 读写打开一个文本文件,允许读和写。
w 打开只写文件,若文件存在则文件长度清为0,即该文件内容会消失。若文件不存在则建立该文件。
w+ 打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。
a 以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。(EOF符保留)
a+ 以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 (原来的EOF符不保留)
wb 只写打开或新建一个二进制文件;只允许写数据。
wb+ 读写打开或建立一个二进制文件,允许读和写。
wt+ 读写打开或着建立一个文本文件;允许读写。
at+ 读写打开一个文本文件,允许读或在文本末追加数据。
ab+ 读写打开一个二进制文件,允许读或在文件末追加数据。
上述的形态字符串都可以再加一个b字符,如rb、w+b或ab+等组合,加入b 字符用来告诉函数库打开的文件为二进制文件,而非纯文字文件。不过在POSIX系统,包含Linux都会忽略该字符。由fopen()所建立的新文件会具有S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH(0666)权限,此文件权限也会参考umask
值。
有些C编译系统可能不完全提供所有这些功能,有的C版本不用"r+","w+","a+",而用"rw","wr","ar"等,读者注意所用系统的规定。
官方文档这么说
"r" | read: Open file for input operations. The file must exist. |
"w" | write: Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file. |
"a" | append: Open file for output at the end of a file. Output operations always write data at the end of the file, expanding it. Repositioning operations (fseek, fsetpos, rewind) are ignored. The file is created if it does not exist. |
"r+" | read/update: Open a file for update (both for input and output). The file must exist. |
"w+" | write/update: Create an empty file and open it for update (both for input and output). If a file with the same name already exists its contents are discarded and the file is treated as a new empty file. |
"a+" | append/update: Open a file for update (both for input and output) with all output operations writing data at the end of the file. Repositioning operations (fseek, fsetpos, rewind) affects the next input operations, but output operations move the position back to the end of file. The file is created if it does not exist. |
相关文章推荐
- fopen参数中有b与没有b的区别
- C中fopen的mode参数中,b的使用区别
- C中fopen的mode参数中,b的使用区别
- Java中如何区别Post和Get的参数?
- 反射中使用值类型与引用类型的参数的区别
- OOP 术语:Arguments(参量)和 Parameters(参数)的区别
- php fopen() mode参数
- fopen里面那个二进制打开和ascii打开有什么区别
- winsock与unix posix中select参数的区别
- .net程序员的盲点(一):参数修饰符ref,out ,params的区别
- 读取容器配置参数---context-param和init-param区别
- 引用参数和输出参数的2个区别(以前偶只知道第一个)
- 参数修饰符ref,out ,params的区别
- .net程序员的盲点(一):参数修饰符ref,out ,params的区别
- .net程序员的盲点(一):参数修饰符ref,out ,params的区别
- c#.net中参数修饰符ref,out ,params得区别
- 调用oracle存储过程的例子,其参数的传递方法与SQLSERVER有区别注意区分
- 通过值传递引用类型和通过引用传递引用类型参数的区别
- C语言中指针变量作为函数参数和一般变量作为函数参数的区别
- 参数修饰符ref,out ,params的区别