I am currently working on my assignment about a simple text editor that can open, add line and delete line and so and so...
I designed an algorithm to add new line to the doc and it works for the first time but didnt work after it, I dont know where the problems is(should be inside the function faddline), highly appreciate for your help :)
int fop(FILE *dfp)
{
int l=1;
char content[200];
if( dfp == 0)
printf("Unable to open file!\n");
else
{
while(fgets(content,200,dfp)!= NULL)
{
printf("line %d: %s",l,content);
l++;
}
printf("\n");
}
return l;
}
void faddline(FILE *fp,int line,char* content,int maxline,int *tipsy)
{
int i=1,l=1;
char dummy[200];
FILE *stream;
if(*tipsy==0)
{
stream = fopen("dummy.txt","w");
while(fgets(dummy,200,fp)!=NULL)
{
if(i==line)
fputs(content,stream);
fputs(dummy,stream);
i++;
}
}
if(*tipsy==1)
{
stream = fopen("dummy.txt","a+");
while(fgets(dummy,200,stream)!=NULL)
{
if(i==line)
fputs(content,stream);
i++;
}
}
if(line>i)
fputs(content,stream);
fclose(stream);
stream = fopen("dummy.txt","r");
fop(stream);
(*tipsy) = 1;
}
while(1)
{
printf("\nO)pen file A)dd a line D)elete a line\nR)eplace word S)ave file Q)uit\nAction> ");
gets(opt);
switch(opt[0])
{
case('o'):
case('O'):
printf("Open file: ");
gets(filepath);
fp = fopen(filepath,"r");
po = fop(fp);
break;
case('a'):
case('A'):
fp = fopen(filepath,"r");
if(fp == 0)
{
printf("Please open a file before editing!\n");
break;
}
printf("Add before line: ");
scanf("%d", &line);
printf("New line content: ");
gets(dummy);
gets(content);
strcat(content,"\n");
faddline(fp,line,content,po,&tipsy);
break;
default:
printf("Invaild action!\n");
break;
}
}
return 0;
}