0064.磁带文件批处理算法C语言实例
数据结构与算法 2022年3月19日
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAXKEY INT_MAX
typedef struct{
int key;
int balance;
}Account;
typedef struct{
int key;
int amount;
}Item;
Account * P(Item gr)
{
Account *ac;
if((ac=(Account *)malloc(sizeof(Account))) == NULL)
{
printf("malloc error.\n");
exit(0);
}
ac->key = gr.key;
ac->balance = gr.amount;
return ac;
}
Account * Q(Account fr, Item gr)
{
Account *ac;
if((ac=(Account *)malloc(sizeof(Account))) == NULL)
{
printf("malloc error.\n");
exit(0);
}
ac->key = fr.key;
ac->balance = fr.balance+gr.amount;
return ac;
}
void MergeFile(FILE *f, FILE *g, FILE *h)
{
Account fr, *nfr;
Item gr;
rewind(f);
rewind(g);
fread(&fr, sizeof(Account), 1, f);
fread(&gr, sizeof(Item), 1, g);
while(!feof(f) || !feof(g))
{
if(fr.key<gr.key)
{
fwrite(&fr, sizeof(Account), 1, h);
if(!feof(f))
fread(&fr, sizeof(Account), 1, f);
}
else if(fr.key==gr.key)
{
nfr = Q(fr, gr);
if(nfr->balance != 0)
fwrite(nfr, sizeof(Account), 1, h);
if(!feof(f))
fread(&fr, sizeof(Account), 1, f);
if(!feof(g))
fread(&gr, sizeof(Item), 1, g);
}
else if(fr.key>gr.key)
{
fwrite(P(gr), sizeof(Account), 1, h);
if(!feof(g))
fread(&gr, sizeof(Item), 1, g);
}
}
}
void main()
{
FILE *f, *g, *h;
Account ac, nac, max;
Item it;
if((f=fopen("F", "wb+"))==NULL || (g=fopen("G", "wb+"))==NULL || (h=fopen("H", "wb+"))==NULL)
{
printf("Can not open i/o file.\n");
exit(0);
}
max.key = MAXKEY;
max.balance = 0;
printf("Input F Data:\n");
scanf("%d,%d", &ac.key, &ac.balance);
while(ac.key>0)
{
fwrite(&ac, sizeof(Account), 1, f);
scanf("%d,%d", &ac.key, &ac.balance);
}
fwrite(&max, sizeof(Account), 1, f);
printf("Input G Data:\n");
scanf("%d,%d", &it.key, &it.amount);
while(it.key>0)
{
fwrite(&it, sizeof(Item), 1, g);
scanf("%d, %d", &it.key, &it.amount);
}
fwrite(&max, sizeof(Item), 1, g);
MergeFile(f, g, h);
printf("H Data:\nKey\tBalance\n");
rewind(h);
fread(&nac, sizeof(Account), 1, h);
while(!feof(h))
{
printf("%d\t%d\n", nac.key, nac.balance);
fread(&nac, sizeof(Account), 1, h);
}
fclose(f);
fclose(g);
fclose(h);
}