Saturday, November 14, 2009

Chap12[C]d Sorting to alphabetical order in a file

Suppose a file contains student’s records with each record containing name and age of a student. Write a program to read these records and display them in sorted order by name.

Program to input students name
#include "stdio.h"

void main()
{
char j='y';
FILE *fp;

struct record
{
char name[20];
int age;
};
struct record a;

fp=fopen("c:\\ctxt\\record.txt","a");
if(fp==NULL)
{
puts("Cannot open file");
exit();
}
while(j=='y')
{
printf("\nKey in the name of the student\n");
scanf("%s",a.name);
printf("\nKey in the age of the student\n");
scanf("%d",&a.age);
fprintf(fp,"%s %d\n",a.name,a.age);
printf("\nAdd another record?(Y/N)");
fflush(stdin);
j=getche();
}
fclose(fp);
}

Program to sort students name


#include "stdio.h"
struct record
{
char name[10];
int age;
};
void main()
{
FILE *fp,*ft;

int i,f=1;

struct record a[5000];

clrscr();


fp=fopen("c:\\ctxt\\record.txt","r");
if(fp==NULL)
{
puts("Cannot open file");
exit();
}
for(i=0;i<5000;i++)
{
if(f==1)
{
if((fscanf(fp,"%s%d",a[i].name,&a[i].age)==EOF))
f=0;
}
if(f==0)
a[i].name[0]='\0';

}

funcsort(a,4);

for(i=0;a[i].name[0]!='\0';i++)
printf("\nName is %s. Age is %d",a[i].name,a[i].age);
printf("\nFile sorted according to alphabetical order");

ft=fopen("c:\\ctxt\\record2.txt","w");
for(i=0;a[i].name[0]!=0;i++)
fprintf(ft,"%s %d\n",a[i].name,a[i].age);
fclose(fp);
fclose(ft);
remove("c:\\ctxt\\record.txt");
rename("c:\\ctxt\\record2.txt","c:\\ctxt\\record.txt");

}
/* Function "funcsort()" is in picture below type it in for it to work */