GreensnoWorld
记录点滴,分享乐趣,一块凝固的时间
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);
}
LIJG
余本顽劣,生于紫云下,长于汝水滨。早年求学,兴趣广泛,好高骛远,学无所成,仓皇入世。兴趣所致,投身互联网,求知未证,而立已至,始悟光阴荏苒,终需务实钻研。故有此站,记录时光,积累点滴,验证所学,分享愚见。指舞方寸间,心系万千年。
留言