Write a program to sort the lines according to their length in a file.
#include<stdio.h> #include<string.h> #include<stdlib.h> #include"fileinfo.h" void Sort_Accordig_to_Line_Length(FILE*,char*); int main() { FILE *fp; char file[32]; printf("Enter file name = "); scanf("%[^\n]",file); fp = fopen(file,"r"); if(fp == NULL) { printf("file is not present in this directoty\n"); return 0; } Sort_Accordig_to_Line_Length(fp,file); return 0; } void Sort_Accordig_to_Line_Length(FILE *fp,char *name) { char **p,ch,temp[100],*t; int j,i,LineCount,StrLenMax; LineCount = Get_Total_Lines(fp); StrLenMax = Get_Max_String_Length(fp); printf("%d %d\n",LineCount,StrLenMax); p = (char**)malloc(sizeof(char*) * LineCount); for(i = 0; i < LineCount;i++) { p[i] = (char*)malloc(StrLenMax+1); fgets(p[i],StrLenMax+1,fp); } t = (char*)malloc(sizeof(StrLenMax+1)); for(i = 0;i < LineCount;i++) { for(j = i + 1; j < LineCount;j++) { if((strlen(p[i])) > (strlen(p[j]))) { t = p[i]; p[i] = p[j]; p[j] = t; } } } fclose(fp); fp = fopen(name,"w"); for(i = 0;i< LineCount;i++) { //fprintf(fp,"%s\n",p[i]); fputs(p[i],fp); } fclose(fp); printf("Sorting Done....\n"); }
Note: File named d1 is present in the current working directory.
Output
cat d1 Lot To Learn BlackBerry Z10 Iphone Incredible India
Output
./a.out Enter file name = d1 4 17 Sorting Done....
cat d1 Iphone Lot To Learn BlackBerry Z10 Incredible India