Click here to Skip to main content
14,428,153 members
Rate this:
Please Sign up or sign in to vote.
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


#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 20-Jun-13 0:18am
v2
Rate this:
Please Sign up or sign in to vote.

Solution 1

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. :-)
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

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.
   

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100