Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define EXCH_CPY(x, y) memcpy(&(x), &(y), sizeof (x))
#define EXCH(x,y) {struct elecVotes tmp; EXCH_CPY(tmp, x), EXCH_CPY(x, y); EXCH_CPY(y, tmp);}
#define CMP(x, y) ((x).votes < (y).votes)
struct elecVotes
{
char name[3];
int votes;
int income;
};
struct incomeTmp
{
char name[3];
int income;
};
void bubSort(struct elecVotes a[], int left, int right);
int main()
{
struct elecVotes array[51];
struct incomeTmp array2[51];
int i;
int j;
FILE* file1;
FILE* file2;
file1 = fopen("elecvotes.txt", "r");
if (file1 == NULL) return -1;
file2 = fopen("income.txt", "r");
if (file2 == NULL) return -1;
FILE* file3; /* Warning: ISO C90 forbids mixed declarations and code */
file3 = fopen("states_by_income.txt", "w");
for (i = 0; i < 51; i++)
{
fscanf(file1,"%2s %d", array[i].name, &(array[i].votes));
printf("%2s %2d\n", array[i].name, array[i].votes);
}
for (i = 0; i < 51; i++)
{
fscanf(file2,"%2s %5d", array2[i].name, &(array2[i].income));
printf("%2s %2d\n", array2[i].name, array2[i].income);
}
i = 0;
j = 0;
while ((i < 51) && (j < 51))
{
if (strcmp(array[i].name, array2[j].name) == 0)
{
array[i].income = array2[j].income;
printf("%2s %2d %d\n", array[i].name, array[i].votes, array[i].income);
i++;
j = 0;
}
else
{
j++;
}
}
bubSort(array, 0, 51);
for (i = 0; i < 51; i++)
{
fprintf(file3,"%2s %2d $%d\n", array[i].name, array[i].votes, array[i].income);
}
fclose(file1);
fclose(file2);
fclsoe(file3);
return EXIT_SUCCESS;
}
void bubSort(struct elecVotes a[], int left, int right)
{
int i, j;
for (i = left; i < right; i++)
{
for (j = right; j < i; j--)
{
if (CMP(a[j], a[j-1])) EXCH(a[j-1], a[j]);
}
}
}