您的位置:首页 > 编程语言 > C语言/C++

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

2014-03-19 00:13 393 查看
用文件来存储用户储存的信息,整形的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;
}

图片演示:





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息