Write a program to Replace a specified Line in a Text File.
C Program
#include <stdio.h>#include <stdbool.h>int main(){FILE *fileptr1, *fileptr2;char filechar[4000];char ch;int lineNum, count = 1;printf("Enter file name: ");scanf("%s", filechar);//open file in read modefileptr1 = fopen(filechar, "r");ch = getc(fileptr1);//print the contents of file .while (true){printf("%c", ch);ch = getc(fileptr1);if (ch == EOF){break;}}printf("\n");printf("Enter line number to be replaced : ");scanf("%d", &lineNum);//take fileptr1 to start point of the//filerewind(fileptr1);//open file in read modefileptr2 = fopen("temp.txt", "w");ch = getc(fileptr1);while (true){if (ch == EOF){break;}//if new line then count lines countif (ch == '\n'){count++;}//copy the content to other file//before the line number to be deletedif (count != lineNum){putc(ch, fileptr2);}else{//delete the current linewhile ((ch = getc(fileptr1)) != '\n'){}//read and skip the line ask for new textprintf("Enter the new text: ");//flush the input streamfflush(stdin);//inert new lineputc('\n', fileptr2);while ((ch = getchar()) != '\n'){putc(ch, fileptr2);}//insert new linefputs("\n", fileptr2);count++;}//continue till EOF is encounteredch = getc(fileptr1);}//close the filesfclose(fileptr1);fclose(fileptr2);//remove from fileremove(filechar);rename("temp.txt", filechar);//open file in read modefileptr1 = fopen(filechar, "r");//reads the character from filech = getc(fileptr1);//until last character of file is encounteredwhile (true){if (ch == EOF){break;}else{printf("%c", ch);ch = getc(fileptr1);}}//close the filefclose(fileptr1);return 0;}
Input File:studentrecord.txt
Name = Rahul, marks = 67 no Name = Suman, marks = 65 Name = Jeet, marks = 56 Name = Anuj, marks = 67
Input:
Enter file name: C:\Users\studentrecord.txt Enter line number to be replaced : 2
Enter the new text: Name = Anil, marks = 34
Output File: studentrecord.txt
Name = Rahul, marks = 67 Name = Anil, marks = 34 Name = Suman, marks = 65 Name = Jeet, marks = 56 Name = Anuj, marks = 67
No comments:
Post a Comment