Respuesta :
Answer:
#define MAX 50
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct address
{
char name[MAX];
char street[MAX];
char city[MAX];
char zip[10];
};
void in(struct address *, int *);
void sort(struct address *, int);
void out(struct address *, int);
int main(){
struct address *ADDRESS = (struct address *)malloc(50*sizeof(struct address));
int n=0;
in(ADDRESS, &n);
sort(ADDRESS, n);
out(ADDRESS, n);
}
void in(struct address *ADDRESS, int *num)
{
FILE *fp;
char fname[MAX];
printf("Enter input file name: ");
scanf("%s", fname);
fp = fopen(fname, "r");
if (fp == NULL)
{
printf("Unable to open file");
exit(1);
}
int a = 0;
while (!feof(fp))
{
//ADDRESS = (struct address *)realloc(ADDRESS, (a + 1) * sizeof(struct address));
if(a>=50)
break;
fscanf(fp, "\n%[^\n]s", (ADDRESS+a)->name);
fscanf(fp, "\n%[^\n]s", (ADDRESS+a)->street);
fscanf(fp, "\n%[^\n]s", (ADDRESS+a)->city);
fscanf(fp, "\n%[^\n]s", (ADDRESS+a)->zip);
a++;
}
printf("Successfully %d read from file\n", a);
*num = a;
}
void sort(struct address *ADDRESS, int num){
int i, j;
for(i=0; i<num; i++){
for(j=i+1; j<num;j++){
if(strcmp((ADDRESS+i)->zip, (ADDRESS+j)->zip)>0){
struct address t = *(ADDRESS+i);
*(ADDRESS+i) = *(ADDRESS+j);
*(ADDRESS+j) = t;
}
}
}
}
void out(struct address *ADDRESS, int num)
{
FILE *fp;
char fname[MAX];
printf("Enter output file name: ");
scanf("%s", fname);
fp = fopen(fname, "w");
if (fp == NULL)
{
printf("Unable to open file");
exit(1);
}
int a;
for(a=0; a<num; a++)
{
fprintf(fp, "%s\n", (ADDRESS+a)->name);
fprintf(fp, "%s\n", (ADDRESS+a)->street);
fprintf(fp, "%s\n", (ADDRESS+a)->city);
fprintf(fp, "%s\n", (ADDRESS+a)->zip);
}
printf("Successfully %d Write to file\n", a);
fclose(fp);
}
Explanation: