Sorting Numbers in File and Writing to Other File Through C Linux Code

/*Code for taking numbers from an input file sort it and write it to another output file.
  Input file contains 216543 
 Output file contains 123456 */
#include<stdio.h>
int main()
{
        FILE *f1,*f2;
        int i,j,temp,v[6],ch;
        f1=fopen("data.in","r");
        f2=fopen("data.out","w+");

        for(i=0;i<6;i++)
                fscanf(f1,"%d",&v[i]);

        for(i=0;i<6;i++)
        {
                for(j=i+1;j<6;j++)
                {
                        if(v[i]>v[j])
                        {
                                temp=v[i];
                                v[i]=v[j];
                                v[j]=temp;
                        }
                }
        }
        for(i=0;i<6;i++)
                fprintf(f2,"%d\n",v[i]);

        close(f1);
        close(f2);
        return 0;
}

------------
/*
Code for taking numbers from an input file sort it and write it to an output file.
   Input file 216543
   Output file 123456
by counting the number of lines  
*/
#include<stdio.h>
int main()
{
        FILE *f1,*f2;
        int i,j,temp,v[10],ch,n=0;
        f1=fopen("data.in","r");
        f2=fopen("data.out","w");

char line[1024];

n=0;
while(fgets(line,sizeof(line),f1)!=NULL)
n++;
/*set the file pointer to beginning*/
fseek(f1,0,SEEK_SET);


        for(i=0;i<n;i++)
                fscanf(f1,"%d",&v[i]);

        for(i=0;i<n;i++)
        {
                for(j=i+1;j<n;j++)
                {
                        if(v[i]>v[j])
                        {
                                temp=v[i];
                                v[i]=v[j];
                                v[j]=temp;
                        }
                }
        }
        for(i=0;i<n;i++)
                fprintf(f2,"%d\n",v[i]);

        close(f1);
        close(f2);
        return 0;
}

No comments:

Post a Comment