C语言实现文件读写

键盘读入字符串写到文件中,再从文件读出显示在控制台
#include<stdio.h>
#include<string.h>
int main()
{
	FILE *fp;
	char string[6];//方括号中是几就输入几个字符串
	if( (fp=fopen("file.txt","w"))==NULL )
	{
		printf("cannot open file");
		return 0;
	}
	while(strlen(gets(string)) > 0)
	{
		fputs(string,fp);
		fputs("\n",fp);
	}
	fclose(fp);

	if( (fp=fopen("file.txt","r"))==NULL)
	{
		printf("cannot open file\n");
		return 0;
	}
	while(fgets(string,6,fp)!=NULL)
	{
		fputs(string,stdout);//系统自动打开stdout文件
	}
	fclose(fp);
}
合并两个文件的内容,并输出到第三个文件
#include<stdio.h>
#include<string.h>
int main()
{
	FILE *fp1,*fp2,*fp3;
	char str1[10],str2[10];
	printf("输入两串字母\n");
	scanf("%s",str1);
	scanf("%s",str2);
	
	//A,B两个文件赋值
	if((fp1=fopen("A.txt","w"))==NULL)
	{
		printf("cannot open file\n");
		return 0;
	}		
	fputs(str1,fp1);		
	fclose(fp1);

	if((fp2=fopen("B.txt","w"))==NULL)
	{
		printf("cannot open file\n");
		return 0;
	}		
	fputs(str2,fp2);		
	fclose(fp2);
	
	//拷贝到第三个文件
	if((fp1=fopen("A.txt","r"))==NULL)
	{
		printf("cannot open file\n");
		return 0;
	}
	if((fp2=fopen("B.txt","r"))==NULL)
	{
		printf("cannot open file\n");
		return 0;
	}
	if((fp3=fopen("C.txt","a"))==NULL)
	{
		printf("cannot open file\n");
		return 0;
	}
	while(!feof(fp1))
	{
		fputc(fgetc(fp1),fp3);
	}
	while(!feof(fp2))
	{
		fputc(fgetc(fp2),fp3);
	}
	fclose(fp1);
	fclose(fp2);
	fclose(fp3);
}
输入学生信息并转存到磁盘文件
#include<stdio.h>
#define SIZE 4
struct student_type
{
	char name[10];
	int num;
	int age;
	char addr[15];
};
struct student_type stud[SIZE];

void save();
void display();
void main()
{
	int i;
	for(i=0;i<SIZE;i++)
	{
		scanf("%s %d %d %s",stud[i].name, &stud[i].num, &stud[i].age, stud[i].addr);
	}

	save();//转存
	display();
}

void save()
{
	FILE *fp;
	int i;
	if((fp=fopen("E:\\计算机导论作业\\加密文档","wb"))==NULL)
	{
		printf("cannot open file\n");
		return;
	}
	for(i=0;i<SIZE;i++)
	{
		if(fwrite(&stud[i], sizeof(struct student_type),1,fp)!=1)
			printf("file write error\n");
	}
	fclose(fp);
}

void display()
{
	FILE *fp;
	int i;
	if((fp=fopen("E:\\计算机导论作业\\加密文档","rb"))==NULL)
	{
		printf("cannot open file\n");
		return;
	}
	for(i=0;i<SIZE;i++)
	{
		fread(&stud[i], sizeof(struct student_type), 1, fp);
		printf("%-10s %4d %4d %-15s\n",stud[i].name, stud[i].num, stud[i].age, stud[i].addr);
	}
	fclose(fp);
}
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值