fopen 中 按文本读写与按二进制读写 实例

参考:http://blog.csdn.net/hinyunsin/article/details/6401854


#include <stdio.h>

int main(int argc, char *argv[])
{
	char he[20] = "hello world\n";
	
	FILE *outfile = fopen("t.txt", "wt");
	fwrite(he, sizeof(char), 20, outfile);
	fclose(outfile);
	
	outfile = fopen("b.txt", "wb");
	fwrite(he, sizeof(char), 20, outfile);
	fclose(outfile);

	return 0;
}

用WinHex查看本地的两个文件

t.txt

b.txt


可以看到按文本写时 fopen 把 '\n' 替换为了 0D0A


对应的,读文件时


#include <stdio.h>
#include <string.h>

void echo(char *sz)
{
	int i = 0;
	while(sz[i])
	{
		printf("%x ", sz[i]);
		++i;
	}
	printf("\n");
}

int main(int argc, char *argv[])
{
	char he[20];
	
	FILE *infile = fopen("t.txt", "rt");
	fread(he, sizeof(char), 20, infile);
	echo(he);
	fclose(infile);
	
	infile = fopen("b.txt", "rt");
	fread(he, sizeof(char), 20, infile);
	echo(he);
	fclose(infile);
	
	infile = fopen("t.txt", "rb");
	fread(he, sizeof(char), 20, infile);
	echo(he);
	fclose(infile);

	infile = fopen("b.txt", "rb");
	fread(he, sizeof(char), 20, infile);
	echo(he);
	fclose(infile);

	return 0;
}


第一行,以文本方式打开t.txt,fopen会将0d0a替换为0a

第二行,以文本方式打开b.txt,返回原内容

第三行,以二进制方式打开t.txt,fopen不作替换,直接读取0d0a

第四行,以二进制方式打开b.txt,返回原内容

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值