C —— 文件读写

C 的标准输入输出库 stdio 中提供了对文件进行读写的函数。

打开文件
函数签名:FILE * fopen ( const char * filename, const char * mode );
返回说明:如果成功打开该文件,则返回指向该文件的 FILE 对象的指针
参数说明:

  1. filename:需要打开的文件名
  2. mode:打开文件的模式

关于参数 mode 的取值:

说明
"r"read
"w"write
"a"append
"r+"read/update
"w+"write/update
"a+"append/update

详细说明请参考:http://www.cplusplus.com/reference/cstdio/fopen/

关闭文件
函数签名:int fclose ( FILE * stream );
返回说明:如果成功关闭该文件,则返回 0
参数说明:

  1. stream:指向该文件的 FILE 对象的指针

详细说明请参考:http://www.cplusplus.com/reference/cstdio/fclose/

写入文件
函数签名:int fputs ( const char * str, FILE * stream );
返回说明:成功时返回非负值
参数说明:

  1. str:需要写入的字符串常量
  2. stream:指向该文件的 FILE 对象的指针

详细说明请参考:http://www.cplusplus.com/reference/cstdio/fputs/

读取文件
函数签名:char * fgets ( char * str, int num, FILE * stream );
返回说明:成功时传入的参数 str 的值
参数说明:

  1. str:指向在其中复制字符串读取的字符数组的指针
  2. num:要复制到str中的最大字符数(包括终止的空字符)
  3. stream:指向该文件的 FILE 对象的指针

详细说明请参考:http://www.cplusplus.com/reference/cstdio/fgets/

简单示例

#include<stdio.h>

int main() {
	const char *filename = "/io.txt";
	// 写
	{
		FILE *f = fopen("/io.txt", "w+");
		int r = fputs("Hello World.\n —— marvelousness", f);
		if(r > -1) {
			r = fclose(f);
			if(r == 0) {
				// printf("写入完成.\n");
			}
		}
	}
	// 读
	{
		FILE *f = fopen("/io.txt", "r");
		char buff[1024];
		while(fgets(buff, 1024, f) != NULL) {
			printf("%s", buff);
		}
		int r = fclose(f);
	}
	
	return 0;
}

执行结果:

Hello World.
 —— marvelousness
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值