C语言 FileStreaming fopen&fclose

本文详细介绍了fopen函数的使用方法,包括参数解释、各种模式的含义及示例代码。涵盖了r、w、a、r+、w+、a+等模式的特性,以及如何处理二进制文件和确认文件是否存在的方法。

fopen

FILE * fopen ( const char * filename, const char * mode );
参数描述
filenameC字符串,文件名
mode
mode描述
r"read: Open file for input operations. The file must exist.
“w”write: 创建新文件,如果已存在,则覆盖
“a”append: 追加,如果文件不存在,则创建.光标在末尾,忽略fseek, fsetpos, rewind
“r+”read/update: Open a file for update (both for input and output). The file must exist.
“w+”write/update: 创建新文件,如果已存在,则覆盖
“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.
  1. mode:使用b来处理二进制文件,如"rb",“wb”,“ab”,“r+b”,“w+b”
  2. mode:C2011中加了’x’,来确认文件是否存在,而不是直接覆盖文件
  3. mode:"+",文件stream在写后的读操作,会先调用flushed(`fflush)或repositioned((fseek, fsetpos, rewind)
  4. mode:"+",读后的写操作,需要先调用fseek, fsetpos, rewind

例子:

#pragma warning(disable:4996)

#include<stdio.h>
#include<stdlib.h>

int main()
{
	FILE * pFile;
	pFile = fopen("test.txt", "w");
	fputs("fopen example", pFile);
	fclose(pFile);
	return 0;
}

fclose

  1. 关闭文件,在之前刷新缓冲区
参数描述
streamFILE object
返回描述
成功返回0
失败EOF(-1)

freopen

  1. 重定向已经打开的流
FILE *freopen(const char *filename, const char *mode, FILE *stream)
参数描述
filenameC字符串,要打开的文件名
modeC字符串
streamFILE指针,要被重新打开的流
#pragma warning(disable:4996)

#include<stdio.h>
#include<stdlib.h>

int main()
{
	FILE *fp;
	fp = freopen("test.txt", "w", stdout);
	printf("%s\n","将标准输出的流重定向到文件"); //printf本应该打印在控制台,现在写入了文件
	fclose(fp);
}

参考:
http://www.gnu.org/software/libc/manual/html_node/I_002fO-on-Streams.html#I_002fO-on-Streams

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值