This blog is under construction

Tuesday 30 July 2013

C program to replace articles with space in a text file

Write a C program to replace articles with space in a text file.


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

  int main() {
        FILE *fp1, *fp2;
        int i, flag = 0, character;
        char filename[MAX], temp[] = {"temp.txt"};

        /* vowels in english alphabet */
        char vowels[] = {'a', 'e', 'i', 'o', 'u',
                         'A', 'E', 'I', 'O', 'U'};

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

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

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

        fp2 = fopen(temp, "w");

        if (!fp2) {
                printf("Unable to open temporary file!!\n");
                return 0;
        }

        /*
         * reading the contents of the input 
         * file character by character
         */
        while ((character = fgetc(fp1)) != EOF) {
                for (i = 0; i < sizeof(vowels); i++) {
                        if (character == vowels[i]) {
                                flag = 1;
                                character = ' ';
                                break;
                        }
                }

                if (flag) {
                        /* replace vowel with space */
                        fputc(character, fp2);
                        flag = 0;
                } else {
                        fputc(character, fp2);
                }
        }

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

        /* remove the source file */
        remove(filename);

        /* rename the temporary file to source file name */
        rename(temp, filename);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ cat dest.txt 
  For loop
  While loop
  do while loop
  structure
  union
  Files
  Conditional statements

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your file name: dest.txt

  jp@jp-VirtualBox:~/$ cat dest.txt 
  F r l  p
  Wh l  l  p
  d  wh l  l  p
  str ct r 
   n  n
  F l s
  C nd t  n l st t m nts






SEE ALSO

    No comments:

    Post a Comment