C语言随机读写文件DEMO

【FROM C 语言实战105例中的第37例 随机读写文件】


/*随机读写文件第37例*/
/*来源于C语言实战105例*/
#include<stdio.h>
#include <stdlib.h>
#define NUM 3
int main(void)
{
	FILE *fp1;
	int i,err;
	struct rec
	{
		char id[10];
		char name[15];
		char department[15];
	}record[NUM];
	printf("***********************************************************\n");
	printf("** This program is to show the random file input & output**\n");
	printf("***********************************************************\n");
	/* 只写打开或新建一个二进制文件;只允许写数据。*/
	if ((err=fopen_s(&fp1,"d:\\infile.txt","wb"))!=0)
	{
		fprintf_s(stderr,"cannot open file");
		exit(1);
	}
	for (i=0;i<NUM;i++)
	{
		printf("please input id:");
		fscanf_s(stdin,"%s",record[i].id,10);
		printf("Please input name:");
		fscanf_s(stdin,"%s",record[i].name,15);
		printf("Please input department:");
		fscanf_s(stdin,"%s",record[i].department,15);
		fwrite(&record[i],sizeof(struct rec),1,fp1);  //成块写入
	}
	fclose(fp1);
	/*rb+ 读写打开一个二进制文件,允许读数据。*/
	if ((err=fopen_s(&fp1,"d:\\infile.txt","rb+"))!=0)
	{
		fprintf_s(stderr,"cannot open file\n");
		exit(1);
	}
	printf("************************************\n");
	printf("%-10s%-15s%-15s\n","id","name","department");
	printf("************************************\n");
	/*显示文件全部内容*/
	for (i=0;i<NUM;i++)
	{
		fread(&record[i],sizeof(struct rec),1,fp1);
		printf("%-10s%-15s%-15s\n",record[i].id,record[i].name,record[i].department);
	}
	/*以下进行文件的随机读写*/
	fseek(fp1,2*sizeof(struct rec),0);  //定位文件指针指向第三条记录
	fwrite(&record[1],sizeof(struct rec),1,fp1);
	/*在第三条记录处写入第二条记录*/
	rewind(fp1);   //移动文件指针到指针头  //相当于fseek(fp1,0L,SEEK_SET);
	printf("************************************\n");
	printf("%-10s%-15s%-15s\n","id","name","department");
	printf("************************************\n");
	for (i=0;i<NUM;i++)
	{
		fread(&record[i],sizeof(struct rec),1,fp1);
		printf("%-10s%-15s%-15s\n",record[i].id,record[i].name,record[i].department);
	}
    fclose(fp1);
	system("pause");
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值