For this assessment you are to write a C program that reads
Solution
//pls rate my solution if you like
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 100
struct rec
{
char fname[20];
char lname[20];
int age;
}record[MAX];
int main()
{
//declare in and out as pointer to FILE
FILE *in;
FILE *out;
int i = 0,count;
char s[10];
void sort(struct rec rec1[], int size);
//open file in read mode
in = fopen(\"input.txt\", \"r\");
if (!in)
{
printf(\"not able to open file for reading\ \");
return -1;
}
while (!feof(in))
{
fscanf(in,\"%s%s%s\", record[i].lname, record[i].fname, s);
record[i].age = atoi(s);
i++;
}
count = i;
sort(record, count);
//write record to file
out = fopen(\"output.txt\", \"w\");
if (!out)
{
printf(\"Not able to open file for writing\ \");
return -1;
}
for (i = 0; i < count; i++)
{
fprintf(out, \"%d\\t%s%s\ \", record[i].age,record[i].lname, record[i].fname);
}
fclose(in);
fclose(out);
}
//sort using bubble sort
void sort(struct rec rec1[], int size)
{
char s1[20], s2[20];
int ag,i,j,cmp;
for (i = 0; i < size; i++)
{
for (j = 0; j < size - 1; j++)
{
cmp = strcmp(rec1[j].lname, rec1[j+1].lname);
if (cmp<0)
{
strcpy(s1, rec1[j + 1].lname);
strcpy(s2, rec1[j + 1].fname);
ag = rec1[j + 1].age;
strcpy(rec1[j + 1].lname,rec1[j].lname);
strcpy(rec1[j + 1].fname,rec1[j].fname);
rec1[j + 1].age = rec1[j].age;
strcpy(rec1[j].lname,s1);
strcpy(rec1[j].fname, s2);
rec1[j].age = ag;
}
}
}
}
-----------------------------------------------------------------------------------------------
output.txt file content
115 Ruth,Babe
16 Potter,Harry
40 Potter,Carrie
48 Obama,Barak
46 Jordan,Michael
33 Hamm,Mia
38 Favre,Brett

