This blog is under construction

Tuesday, 30 July 2013

C program to remove numbers in a file

Write a C program to remove numbers in a file.


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

  int main() {
        int ch;
        FILE *fp1, *fp2;
        char fname[MAX], temp[] = "temp.txt";

        /* get the input file from the user */
        printf("Enter your input file name:");
        scanf("%s", fname);

        /* open the input file in read mode */
        fp1 = fopen(fname, "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 temporary file to write!!\n");
                return 0;
        }

        /* copy all contents except numbers */
        while ((ch = fgetc(fp1)) != EOF) {
                if (ch >= '0' && ch <= '9') {
                        continue;
                }
                fputc(ch, fp2);
        }

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

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

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



  Output:
  jp@jp-VirtualBox:~/$ cat data.txt 
  abcd1234efgh
  6789ijkl1234
  mnop5678qrst
  1234uvwx5678
  yzab123 abds
  
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input file name:data.txt

  jp@jp-VirtualBox:~/$ cat data.txt 
  abcdefgh
  ijkl
  mnopqrst
  uvwx
  yzab abds






SEE ALSO

    No comments:

    Post a Comment