C Programming
Computer Programming

C file handling program to remove a specific line from the text file and print the modified content file



Write C file handling program to remove a specific line from the text file and print the modified content file

\* C file handling program to remove a specific line from the text file and print the modified content file *\

# include < stdio.h >
# include < string.h >
# include < stdlib.h >
int   main( )
{

FILE* fp1 ;
FILE* fp2 ;
char ch, filename1[20], filename2[20] ;
int line = 0 ;
int temp = 1 ;

printf("\n Enter the source filename : ") ;
scanf("%s", filename1) ;
fp1 = fopen(filename1, "r") ;
if (fp1 == NULL)
{
      printf("\nUnable to open file\n");
      return -1 ;
}

while (!feof(fp1))
{
      ch = getc(fp1);
      printf("%c", ch) ;
}
rewind(fp1) ;

printf("\nEnter line number to delete the line: ") ;
scanf("%d", &line) ;
fp2 = fopen("temp.txt", "w") ;
while (!feof(fp1))
{
      ch = getc(fp1) ;
      if (ch == '\n')
            temp++ ;

      if (temp != line)
            putc(ch, fp2) ;
}

fclose(fp1) ;
fclose(fp2) ;
remove(filename1) ;
rename("temp.txt", filename1) ;
printf("\n\nModified file:\n") ;

fp1 = fopen(filename1, "r") ;
if (fp1 == NULL)
{
      printf("\nUnable to open file\n") ;
      return -1 ;
}

while (!feof(fp1))
{
      ch = getc(fp1) ;
      printf("%c", ch) ;
}
fclose(fp1) ;
printf("\n") ;
return 0 ;

}

Output of Program :

Output of C file handling program to remove a specific line from the text file and print the modified content file