信息系统修改版 c语言 控制台版

用文件来存储用户储存的信息,整形的id,age和浮点型的salary 和字符串的名字

并且对id来进行查重操作。 缺点是 文件的查重操作必须是上一次保存后信息存储文件有数据后才可以进行。

保存文件的代码:

#include <stdio.h>
#include <string.h>
#define Size 20
int judge(int id){
	FILE *p_judge = fopen("info.txt","rb");
	if(!p_judge){
		return 1;
	}
	int num = 0, flag = 1,judge = 1;
	while(1){
	  judge = fread(&num,sizeof(num),1,p_judge);
    //  printf("%d\n",num);
	  fseek(p_judge,8 + Size,SEEK_CUR) ;
	  if(!judge){
	     break;
	  }
	  if(num == id){
	    flag = 0;
		break;
	  }
	}
	fclose(p_judge);
	p_judge = NULL;
	return flag;  //1 represent not find
}

int main()
{
	FILE *p_file = fopen("info.txt","ab");
	if (!p_file){
		return 0;
	}
	int id,age;
	float money;
	char name[Size],choice = 'Y';
	do {
		printf("Please input id,age,money,name.\n");
        printf("input id: ");
	    scanf("%d",&id);
		int flag = 0;
        flag = judge(id);
		if (!flag){
		    printf("id is same,please input again.\n");
		   	continue;	
		}
		printf("input age: ");
		scanf("%d",&age);
		printf("input money: ");
		scanf("%f",&money);
		getchar();
        printf("input name: ");
		fgets(name,Size,stdin);
		//printf("%s\n",name);
		if (strlen(name) == Size && name[Size-1] != '\n'){
		   scanf("%*[^\n]");
		   scanf("%*c");
		}
	    fwrite(&id,sizeof(id),1,p_file);
		fwrite(&age,sizeof(age),1,p_file);
		fwrite(&money,sizeof(money),1,p_file);
		fwrite(name,sizeof(char),sizeof(name),p_file);
		printf("Do you want to input another piece of information? Y or N\n");
		scanf("%c",&choice);
	}while(choice == 'Y' || choice == 'y');
	fclose(p_file);
	p_file = NULL;
	return 0;
}




读取文件的代码:

#include <stdio.h>
#include <string.h>
#define Size 20
int main()
{
	int id,age;
	float money;
	char name[Size];
	FILE *p_file = fopen("info.txt","rb");
	if(!p_file){
		return 0;
	}
    int judge = 0;
	do{
	  judge = fread(&id,sizeof(id),1,p_file);
	  if(!judge){
	  	break;
	  }
	  fread(&age,sizeof(age),1,p_file);
	  fread(&money,sizeof(money),1,p_file);
	  fread(name,sizeof(char),sizeof(name),p_file);
      printf("%d %d %g %s\n",id,age,money,name);	
	}while(1);
	fclose(p_file);
	p_file = NULL;

	return 0;
}



图片演示:






评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值