This blog is under construction

Tuesday, 30 July 2013

C program to print the words in a file starting with the given character

Write a C program to print the words in a file starting with the given character.


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

  int main() {
        int ch;
        FILE *fp;
        char word[MAX], fname[MAX];

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

        /* get the input character from the user */
        printf("Enter your input character:");
        ch = getchar();

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

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

        /* print the words starting with input character */
        while (!feof(fp)) {
                strcpy(word, "\0");
                fscanf(fp, "%s", word);
                if (word[0] == ch) {
                        printf("%s\n", word);
                }
        }

        /* close the opened file */
        fclose(fp);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ cat dest.txt 
  Anaconda
  Bullock
  Horse
  Apple Banana
  Brother
  Binding


  Cutlet

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input file name: dest.txt
  Enter your input character:B
  Bullock
  Banana
  Brother
  Binding






SEE ALSO

    No comments:

    Post a Comment