C Program to Sort File on Names using Bubble Sort

Problem:

Write a c program to sort file on names using bubble sort. Read the data from the file “employee.txt” and sort on names in alphabetical order (use strcmp) using bubble sort.

C Program / Source Code:

Here is the source code of c program to sort file on names using bubble sort algorithm
/* Aim: Read the data from the file “employee.txt” and sort on names in alphabetical order (use strcmp() function) using bubble sort */

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct employee
{
	char name[20];
	int age;
	int sal;
 
}emp[200];

void main()
{
	struct employee temp;
	FILE *fp;
	int i=0,size,j;
	char ch; 

 
	fp=fopen("emp.txt","r");


	if(fp==NULL)
	{ 
	printf("\n Cannot open the file \n");
	exit(0);
	}


	while(ch!=EOF)
	{
	fscanf(fp,"%s%d%d",emp[i].name,&emp[i].age,&emp[i].sal);  
	ch=fgetc(fp); 
	i++;  
	} 

	size=i-1;

	for(i=1;i<size;++i)
		for(j=0;j<size-i;j++)
			if(strcmp(emp[j+1].name,emp[j].name)<0)
			{
				temp=emp[j];
				emp[j]=emp[j+1];
				emp[j+1]=temp;
			}


	fp=fopen("empsorted.txt","w");

	for(i=0;i<size;i++)
	fprintf(fp,"%s %d %d \n",emp[i].name,emp[i].age,emp[i].sal);

	printf("\n The file is sorted successfully and saved as empsorted.txt. \n \n");

}

/* Output of above code:-

 The file is sorted successfully and saved as empsorted.txt. 

*/

Further Programs: