Exercise 8. WAP to replace a specific line with another text in a file. 1
#include<stdio.h>
int main()
{
FILE *fp, *fp2;
int n=1, line;
char str[80], text[80];
fp=fopen("file.txt","r");
fp2=fopen("temp.txt","w");
printf("Enter line no. to replace: ");
scanf("%d",&line);
printf("Enter new text: ");
fflush(stdin);
gets(str);
do{
fgets(text,80,fp); //read line from file
if(n==line) //skip the line to delete
{
fputs(str,fp2); //write new text in file
fputs("\n",fp2); //write new text in file
}
else
fputs(text,fp2); //write line in file
n++;
}while(!feof(fp));
fclose(fp);
fclose(fp2);
remove("file.txt");
rename("temp.txt","file.txt");
}
1st line
second line
3rd line
1st line
2nd line
3rd line