Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Guys ,

I am learning C, i want to sort the data from the file, How do i do that in C.

There is a code that i have written so far, which open the data from the file


C++
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
   char ch, file_name[25];
   FILE *fp;
 
   printf("Enter the name of file \n");
   gets(file_name);
 
   fp = fopen(file_name,"r"); // read mode
 
   if( fp == NULL )
   {
      perror("Error while opening the file.\n");
      exit(EXIT_FAILURE);
   }
 
   printf("The contents of %s file are :\n", file_name);
 
   while( ( ch = fgetc(fp) ) != EOF )
        
      printf("%c",ch); 
   
   fclose(fp);
   
   
   return 0;
}



how do i stored the data in buffer?

and how do i sort the data in ascending order?
Posted
Updated 19-Jun-13 23:18pm
v2

If you can put all the file content into a memory buffer then use qsort[^]. On the other hand, if the file is to big to fit onto a memory buffer then you should have a look at merge sort[^] algorithm.
 
Share this answer
 
You need a buffer which is great enough: -> use the filesize and allocate with new. But watch out for reading the data with approbiate function and data types for avoiding bugs.

for sorting use best use some sorting functions like bubblesort or quicksort

A simple, portable yet efficient Quicksort implementation in C[^]

After sorting you can write the sorted data in a file and you are done. :-)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900