带缓存的I/O操作代码示例(复习)

/*  带缓存的I/O 操作 */
/*   fopen.c   */

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

int main()
{
	FILE *fp;

	fp = fopen("hello.txt","w");
	if(NULL == fp)
	{
		perror("fopen");
		exit(1);
	}
	else
	{
		printf("Open the hello.txt success!\n");
	}

	fclose(fp);

	return 0;
}





/* fread.c */

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

int main()
{
	FILE *fp;
	char buf[3] = {0};

	fp = fopen("hello.txt","r");
	if(NULL == fp)
	{
		perror("fopen");
		exit(1);
	}

	printf("Read from the txt:\n");
	while(fread(buf,1,2,fp))
	{
		printf("%s",buf);
		memset(buf,0,sizeof(buf));
	}

	fclose(fp);

	return 0;
}







/* fwrite.c */

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

int main(int argc,char **argv)
{
	FILE *fp;
	char buf[20] = {0};


	if(argc < 2)
	{
		printf("Please input the pathname!\n");
		exit(1);
	}

	fp = fopen(argv[1],"w");
	if(NULL == fp)
	{
		perror("fopen");
		exit(2);
	}

	while(1)
	{
		printf("Please input the string:\n");
		scanf("%s",buf);

		if(strcmp(buf,"end") != 0)  //end 结束输入
		{
			fwrite(buf,1,32,fp);
			memset(buf,0,sizeof(buf));
		}
		else
		{
			break;
		}
	}

	fclose(fp);

	return 0;
}





/* 带缓存的I/O的综合应用案例 copy.c */

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

int main(int argc,char **argv)
{
	FILE *fp1,*fp2;
	char buf[64] = {0};

	/* 参数判断 */

	if(argc < 3)
	{
		printf("Input error!\n");
		exit(1);
	}

	/* 打开两个文件 */

	 fp1 = fopen(argv[1],"r");
	 if(NULL == fp1)
	 {
		perror("fopen1");
		exit(2);
	 }

	 fp2 = fopen(argv[2],"w");
	 if(NULL == fp1)
	 {
	 	perror("fopen2");
		exit(3);
	 }

	/* 打开被复制文件  写到复制文件 */

	printf("Copying...\n");
	 while(fread(buf,1,32,fp1))
	 {
		fwrite(buf,1,32,fp2);
		memset(buf,0,sizeof(buf));  //每次进行一次清空,防止复制的内容里面出现奇怪的字符
	 }
	printf("Coping success!\n");

	/* 关闭文件 */

	fclose(fp1);
	fclose(fp2);


	return 0;
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值