C Program to Bubble Sort Records in a text File

Problem:

Sort text file in C. Write a C program to bubble sort a text file. Write a C program to sort a text file "employee.txt" using bubble sort algorithm in C. Write a C program to sort words in a file.

Algorithm or Solution:

Here is the solution of C program to sort a text file using bubble sort algorithm in C programming
  1. Create a structure employee. Create a temp variable for employee structure.
  2. Open the file to sort.
  3. Scan all file and save it to structure employee.
  4. Now use bubble sort on structure with temp variable crated earlier.
  5. Create a new file.
  6. Save the sorted structure to the file.
  7. The file is now sorted and saved to a new file.
  8. Stop.

C Program / Source Code:

Here is the source code of C program to sort a text file using bubble sort algorithm in C
/* Aim: Write a C program to bubble sort a text file */

//this program sorts records or lines in a text file

#include<stdio.h>
#include<stdlib.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(emp[j+1].age<emp[j].age)
	{
	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. 

*/

Related Program: