Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
2. Program will output to file „F2.txt“ first the residents of Tallinn, then Tartu and finally the rest.
*/
typedef struct
{
char name[15];
char telephone[11];
}Person;
typedef struct
{
char street[15];
char city[15];
Person person;
} Address;
enum { MAX_ROW = 20};
void convert(char str[]);
void input(FILE*, Address* address[MAX_ROW]);
void output(FILE* ip, FILE* op, Address* address[MAX_ROW]);
int main(void)
{
FILE *ip, *op;
Address* address[MAX_ROW];
op = fopen("F2.txt","w");
ip = fopen("F1.txt","r");
if (ip==NULL || op==NULL)
{
printf("\n cannot open file\n");
exit(0);
}
input(ip, address);
output(ip, op, address);
fclose(ip);
fclose(op);
return 0;
}
void input(FILE* ip, Address* address[MAX_ROW])
{
int row = 0;
while (row < MAX_ROW && fscanf(ip, "%s, %s, %s, %s",
address[row]->person.name, address[row]->person.telephone,
address[row]->street, address[row]->city ) == 4)
{
row++;
}
}
void output(FILE* ip, FILE* op, Address* address[MAX_ROW])
{
char P[10] = {"Tallinn"};
char T[10] = {"Tartu"};
char total[50];
char fin[MAX_ROW];
int i,e,r;
int count = 0;
convert(P);
convert(T);
for (i=0; i < MAX_ROW; i++ )
{
strcpy(total, address[i]->city);
convert(total);
if (strstr(total, P) != NULL )
{
fin[count] = address[i]; //stores the data found in this structure array
count++;
}
}
for (e=0; e < MAX_ROW; i++ )
{
fprintf(op, "%s\t, %s\t, %s\t, %s\t",
fin[e]->person.name, fin[e]->person.telephone, fin[e]->street, fin[e]->city );
printf("%s\t, %s\t, %s\t, %s\t", fin[e]->person.name,
fin[e]->person.telephone, fin[e]->street, fin[e]->city );
}
for (i=0; i < MAX_ROW; i++ )
{
if (strstr(total, T) != NULL )
{
address[count] = address[i]; //stores the data found in this structure array
count++;
}
}
for (r=0; r < MAX_ROW; r++ ){
fprintf(op, "%s\t, %s\t, %s\t, %s\t", fin[r]->person.name,
fin[r]->person.telephone, fin[r]->street, fin[r]->city);
printf("%s\t, %s\t, %s\t, %s\t", fin[r]->person.name,
fin[r]->person.telephone, fin[r]->street, fin[r]->city);
}
for (i=0; i < MAX_ROW; i++ )
{
if ((strstr(total, P) == NULL ) && (strstr(total, T) == NULL ))
{
fprintf(op,"no result found");
printf("no result found");
}
}
for (i=0; i < MAX_ROW; i++ )
{
{
address[count] = address[i]; //stores the data found in this structure array
count++;
}
}
for (r=0; r < MAX_ROW; r++ ){
fprintf(op, "%s\t, %s\t, %s\t, %s\t", fin[r]->person.name,
fin[r]->person.telephone, fin[r]->street, fin[r]->city );
printf("%s\t, %s\t, %s\t, %s\t", fin[r]->person.name,
fin[r]->person.telephone, fin[r]->street, fin[r]->city );
}
}
void convert(char str[])
{
int i;
for (i = 0; str[i] != '\0'; i++)
{
if (str[i] >= 'A' && str[i] <= 'Z') //checks each character and converts it
{
str[i] = str[i] + 32;
}
}
}