This blog is under construction

Wednesday, 31 July 2013

C program to replace specific line in a file

Write a C program to replace specific line in a file.


  #include <stdio.h>
  #include <string.h>
  #define MAX 256

  int main() {
        FILE *fp1, *fp2;
        int lnum, lineCount = 0;
        char file[MAX], string[MAX];
        char newline[MAX], temp[] = "temp.txt";

        /* get the input file name from the user */
        printf("Enter your input file name:");
        fgets(file, MAX, stdin);
        file[strlen(file) - 1] = '\0';

        /* open the input file in read mode */
        fp1 = fopen(file, "r");

        /* error handling */
        if (!fp1) {
                printf("Unable to open the input file!!\n");
                return 0;
        }

        /* open the temporary file in write mode */
        fp2 = fopen(temp, "w");

        /* error handling */
        if (!fp2) {
                printf("Unable to open a temporary file to write!!\n");
                fclose(fp1);
                return 0;
        }

        /* get the new line from the user */
        printf("Enter your new input line(to replace):");
        fgets(newline, MAX, stdin);

        /* get the line number to delete the specific line */
        printf("Enter the line no of the line you want to replace:");
        scanf("%d", &lnum);

        /*
         * copy all contents to the temporary file other
         * other than line belongs to input line number.
         */
        while (!feof(fp1)) {
                strcpy(string, "\0");
                fgets(string, MAX, fp1);
                if (!feof(fp1)) {
                        lineCount++;
                        /* skip the line at given line number */
                        if (lineCount != lnum) {
                                fprintf(fp2, "%s", string);
                        } else {
                                /* replacing with new input line */
                                fprintf(fp2, "%s", newline);
                        }
                }
        }

        /* close the opened files */
        fclose(fp1);
        fclose(fp2);

        /* remove the input file */
        remove(file);

        /* rename the temporary file */
        rename(temp, file);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ cat second.txt 
  0123456789
  abcdefghij
  0123456789
  abcdefghij
  0123456789

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input file name:second.txt
  Enter your new input line(to replace):abcedfghij
  Enter the line no of the line you want to replace:5

  jp@jp-VirtualBox:~/$ cat second.txt 
  0123456789
  abcdefghij
  0123456789
  abcdefghij
  abcedfghij






SEE ALSO

    No comments:

    Post a Comment