Program for sorting records in a file, Using linked list and insertion sort, records are sorted.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node{
int eno;
char *rec;
struct node_st *next;
};
typedef struct node * NODE ;

NODE  add(NODE  list,int eno,char *rec);
void writetofile(NODE  list,char *fn);

int main(int argc,char* argv[])
{
int nu;
char *buf,*temp;
NODE  list=NULL;
FILE *fp;
if(argc !=2)
{
printf("Usage: sort <filename>");
exit(0);
}
buf=(char *)malloc(80);
temp=(char *)malloc(80);
if((fp=fopen(argv[1],"r"))==NULL)
{
printf("%s file open error",argv[1]);
exit(0);
}
while(fgets(buf,80,fp))
{
strcpy(temp,buf);
nu=atoi(strtok(buf,"|"));
list=add(list,nu,temp);
}
fclose(fp);
writefile(list,argv[1]);
free(buf);
free(temp);

}
void writetofile(NODE  list,char *fn)
{
FILE *fp;
NODE  p;
fp=fopen(fn,"w");
p=(NODE)(malloc(sizeof(struct node_st)));
p=list;
while(p!=NULL)
{
fprintf(fp,"%s",p->rec);
p=p->next;
}
}

NODE  add(NODE  list,int eno,char *rec)
{
NODE  p,q,r=NULL;
p=(NODE)(malloc(sizeof(struct node_st)));
p->rec=(char *)malloc(strlen(rec)+1);
p->eno=eno;
strcpy(p->rec,rec);
if (list==NULL)
{
p->next=NULL;
list=p;
}
else
{
if((list->eno)>(p->eno))
{
p->next=list;
list=p;
}
else
{
for(q=list;q!=NULL&& (q->eno)<(p->eno);q=q->next)
r=q;
p->next=r->next;
r->next=p;
}

}
return list;

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s