您的位置:首页 > 运维架构

fopen()中w 和w+等各个参数的区别

2017-03-29 15:31 169 查看


函数简介

  函数功能: 打开一个文件
  函数原型:FILE * fopen(const char * path,const char * mode);
  相关函数:openfclose,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 (fseekfsetposrewind)
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 (fseekfsetposrewind)
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 函数 CC++