This blog is under construction

Wednesday, 31 July 2013

C program to sort characters in each words of a file

Write a C program to sort characters in each words of a file.


  #include <stdio.h>
  #include <string.h>
  #define MAX 256
  #define INSIDE 1
  #define OUTSIDE 0

  /* sorts the characters in the given word */
  void sortCharacters(char *str) {
        int i, j, temp;

        for (i = 0; i < strlen(str) - 1; i++) {
                temp = str[i];
                for (j = i + 1; j < strlen(str); j++) {
                        if (temp > str[j]) {
                                temp = str[j];
                                str[j] = str[i];
                                str[i] = temp;
                        }
                }
        }
        return;
  }

  int main() {
        FILE *fp;
        char filename[MAX], word[MAX] = "\0";
        int i = 0, ch, pos = OUTSIDE;

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

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

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

        /* sort the words in the given file */
        while ((ch = fgetc(fp)) != EOF) {

                if (ch == '\n' || ch == '\t' || ch == ' ') {
                        /* end of word */
                        word[i] = '\0';

                        /* sorts the given word */
                        sortCharacters(word);

                        /* print the word */
                        printf("%s%c", word, ch);

                        /* moving to start of word */
                        i = pos = OUTSIDE;
                } else if (pos == OUTSIDE) {
                        pos = INSIDE;
                        /* scanning word character */
                        word[i++] = ch;
                } else {
                        /* scanning characters in a word */
                        word[i++] = ch;
                }
        }

        /* closing the opened files */
        fclose(fp);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ cat data.txt 
  all is well
  god is great
  my name is khan
  pursuit of happiness
  a walk to remember

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input file name:data.txt
  all is ellw
  dgo is aegrt
  my aemn is ahkn
  iprstuu fo aehinppss
  a aklw ot beeemmrr





SEE ALSO

    No comments:

    Post a Comment