So i have some code that will allow the user to write anywhere they want inside a text file, thanks to the answers from How do I write to a specific line of file in c? , However i have hit a new obstacle, whenever i write back to the file an annoying random character will always appear at the end of the last word, and if it's on the first line a new line is created before it. I know this has something to do with the file copy but i don't know where, can someone please help?
int main()
{
FILE *fp,*fc;
int lineNum;
int count=0;
int ch=0;
int edited=0;
char t[16];
fp=fopen("start.txt","r");
fc=fopen("end.txt","w");
if(fp==NULL||fc==NULL)
{
printf("\nError...cannot open/create files");
return 1;
}
printf("\nEnter Line Number Which You Want 2 edit: ");
scanf("%d",&lineNum);
while((ch=fgetc(fp))!=EOF)
{
if(ch=='\n')
count++;
if(count==lineNum-1 && edited==0)
{
printf("\nEnter input to store at line %d:",lineNum);
scanf(" %s[^\n]",t);
fprintf(fc,"\n%s\n",t); /
edited=1;
while( (ch=fgetc(fp))!=EOF )
{
if(ch=='\n')
break;
}
}
else
fprintf(fc,"%c",ch);
}
fclose(fp);
fclose(fc);
if(edited==1)
{
printf("\nCongrates...Error Edited Successfully.");
FILE *fp1,*fp2;
char a;
system("cls");
fp1=fopen("end.txt","r");
if(fp1==NULL)
{
puts("This computer is terrible and won't open end");
exit(1);
}
fp2=fopen("start.txt","w");
if(fp2==NULL)
{
puts("Can't open start for some reason...");
fclose(fp1);
exit(1);
}
do
{
a=fgetc(fp1);
fputc(a,fp2);
}
while(a!=EOF);
fclose(fp1);
fclose(fp2);
getch();
}
else
printf("\nLine Not Found");
return 0;
}
(Sorry about ident, i'm in a rush)