In this program, we are going to share C program delete a specific line from a text file. If you are a C programming beginner and want to learn C programming, then keep your close attention in this tutorial as I am going to share a C program delete a specific line from a text file with the output.
Copy below c program and execute it with c compiler to see the output of the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | #include <stdio.h> int main() { FILE *fileptr1, *fileptr2; char filename[40]; char ch; int delete_line, temp = 1; printf("Enter file name: "); scanf("%s", filename); fileptr1 = fopen(filename, "r"); ch = getc(fileptr1); ` while (ch != EOF) { printf("%c", ch); ch = getc(fileptr1); } rewind(fileptr1); printf(" \n Enter line number of the line to be deleted:"); scanf("%d", &delete_line); fileptr2 = fopen("replica.c", "w"); ch = getc(fileptr1); while (ch != EOF) { ch = getc(fileptr1); if (ch == '\n') temp++; //except the line to be deleted if (temp != delete_line) { //copy all lines in file replica.c putc(ch, fileptr2); } } fclose(fileptr1); fclose(fileptr2); remove(filename); rename("replica.c", filename); printf("\n The contents of file after being modified are as follows:\n"); fileptr1 = fopen(filename, "r"); ch = getc(fileptr1); while (ch != EOF) { printf("%c", ch); ch = getc(fileptr1); } fclose(fileptr1); return 0; } |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.