Write a program to carry out the following:
(a) Read a text file ‘INPUT.TXT’
(b) Print each word in reverse order
Example,
Input: PAKISTAN IS MY COUNTRY
Output: NATSIKAP SI YM YRTNUOC
Assume that each word length is maximum of 10 characters and each word is
separated by newline/blank characters.
INPUT.txt file:
PAKISTAN IS MY COUNTRY
C code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char text[1000];
char reverseWord[100];
int i=0;
char* word;
int j;
FILE *fptr;
if ((fptr = fopen("INPUT.txt", "r")) == NULL) {
printf("Error! File cannot be opened.");
exit(1);
}
while ((text[i++] = fgetc(fptr)) != EOF);
text[i-1]='\0';
fclose(fptr);
printf ("Input text: \n%s\n\n",text);
word = strtok(text," ");
printf ("\nText in reverse order: \n");
while (word != NULL){
j=0;
for (i = strlen(word) - 1; i >= 0; i--)
{
reverseWord[j] = word[i];
j++;
}
reverseWord[j] = '\0';
printf ("%s ",reverseWord);
word = strtok (NULL, " ");
}
free(word);
getchar();
getchar();
return 0;
}
Comments
Leave a comment