/*
slip-7
1. Write a command line program for line editor. The file to be edited is taken
as command line argument, an empty file is opened for editing if no argument
is supplied. It should display '$' prompt to accept the line editing commands.
Implement the following commands.
i) a - to append
ii) i n - to insert after nth line
iii) c n1 n2 - to copy line n1 at n2 position
iv) c n1, n2 n3 - to copy range of line at n3 [30 marks]
*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define newnode (struct node *)malloc(sizeof(struct node))
struct node
{
char line[80];
struct node *next,*prev;
}*head=NULL;
int length();
void print();
void append(char *line);
void load(char *);
void add();
void insert(char *,int);
void copy(int,int,int,int);
void load(char *fname)
{
FILE *fp;
char line[80];
fp=fopen(fname,"r");
if(fp==NULL)
{
printf("\nFile cannot boe opened..");
getch();
exit(0);
}
while(!feof(fp))
{
fgets(line,80,fp);
append(line);
}
}
void append(char *line)
{
struct node *f,*s;
f=newnode;
strcpy(f->line,line);
f->next=NULL;
f->prev=NULL;
if(head==NULL)
head=f;
else
{
for(s=head;s->next!=NULL;s=s->next);
s->next=f;
f->prev=s;
s=s->next;
}
}
void print()
{
struct node *f;
int i=1;
for(f=head;f!=NULL;f=f->next)
printf("%d %s",i++,f->line);
}
int length()
{
int cnt=0;
struct node *s;
for(s=head;s!=NULL;s=s->next)
cnt++;
return cnt;
}
void insert(char *line,int from)
{
struct node *f,*s;
int len,i;
if(from-1>length())
{
printf("\nError..");
return;
}
f=newnode;
f->next=NULL;
f->prev=NULL;
strcpy(f->line,line);
if(from==1)
{
f->next=head;
head->prev=f;
head=head->prev;
return;
}
else
{
s=head;
for(i=1;i<(from-1);i++)
s=s->next;
f->next=s->next;
s->next->prev=f;
s->next=f;
f->prev=s;
}
}
main(int argc,char *argv[])
{
int ch;
int i,notok,from,to,range;
char cmd[80],tok[4],line[80];
clrscr();
for(i=0;i<4;i++)
tok[i]=(char )malloc(20);
if(argc==2)
{
head=NULL;
load(argv[1]);
}
while(1)
{
printf("\n?");
flushall();
gets(cmd);
notok=sscanf(cmd,"%s%s%s%s",tok[0],tok[1],tok[2],tok[3]);
switch(cmd[0])
{
case 'q':exit(1);
case 'p':print();
break;
case 'i':from=atoi(tok[1]);
printf("Input Line:");
flushall();
fgets(line,80,stdin);
insert(line,from);
break;
case 'c':from=atoi(tok[1]);
to=atoi(tok[2]);
range=atoi(tok[3]);
copy(notok,from,to,range);
break;
}
}
}
void copy(int notok,int from,int to,int range)
{
int len,i;
struct node *s,*f,*temp;
char line[80];
len=length();
if(from>len)
{
printf("\nError...");
return;
}
if(notok==3)
{
s=head;
for(i=0;i<(from-1);i++)
s=s->next;
insert(s->line,to);
}
if(notok==4)
{
if(to>len || range-1>len)
{
printf("\nError,,,");
return;
}
s=head;
for(i=0;i<(from-1);i++)
s=s->next;
for(i=from;i<=to && s!=NULL;i++)
{
insert(s->line,range++);
s=s->next;
}
}
}