Monday, November 30, 2009

Chap 13[B](a) Reverse words in text file

Write a program to carry out the following:
(a) Read a text file provided at command prompt
(b) Print each word in reverse order
For example if the file contains
INDIA IS MY COUNTRY
Output should be
AIDNI SI YM YRTNUOC


How to use:
1) Compile the below program to obtain .exe file.
2) In turbo C press F9 to compile and go to C:\TC\BIN to find your .exe file
3) Rename your.exe file to any name for example reverse.exe.
4) In the folder where reverse.exe is, create a text file (e.g test.txt) and input any text in it.
5) For vista, in the same folder hold shift and right click anywhere in the folder and click open command prompt here.
6) Then in command prompt type :
reverse test.txt test2.txt
7)The reversed text is found in test2.txt.




#include "stdio.h"
void main(int argc,char *argv[])
{
int i,j,f=1;
FILE *fs,*ft;
char ch,word[25],word2[25];

if(argc!=3)
{
puts("Improper number of arguments");
exit();
}

fs=fopen(argv[1],"r");
if(fs==NULL)
{
puts("\nCannot open source file");
exit();
}

ft=fopen(argv[2],"w");

while(1)
{
word2[0]='\0';
word[0]='\0';
for(i=0;;i++)
{
ch=fgetc(fs);
if(ch==EOF)
{
f=0;
break;
}
if(ch==32)
{
f=2;
break;
}
if(ch==44)
{
f=3;
break;
}
if(ch==46)
{
f=4;
break;
}
if(ch=='\n')
{
f=5;
break;
}
word[i]=ch;

}
word[i]='\0';
for(j=0,i-=1;i>=0;i--,j++)
word2[j]=word[i];

word2[j]='\0';
fputs(word2,ft);
if(f==2)
fputc(32,ft);
if(f==3)
fputc(44,ft);
if(f==4)
fputc(46,ft);
if(f==5)
fputc('\n',ft);
if(f==0)
break;
}
fclose(fs);
fclose(ft);
}

2 comments:

  1. become a follower for free C,C++ And vb code of my blog:
    http://www.a2zhacks.blogspot.com to learn C,C++,VB programming.
    or let us exchange link so as to generate more traffic to our site if yes mail me from my blog

    ReplyDelete
  2. www.myindiancomics.blogspot.com
    visit

    ReplyDelete