Thread: Something is wrong with my file reverse program

  1. #1
    Super unModrator
    Join Date
    Dec 2007
    Posts
    321

    Exclamation Something is wrong with my file reverse program

    It should read a file and give out its reverse in another file. Here it is:

    Code:
    #include<stdio.h>
    int main()
    {
       char temp[200],ch;
       int x,lol;
       int flag=0;
       FILE *inf,*outf;
       inf=fopen("/home/abhishek/Desktop/shakespear.txt","r");
       if(inf==NULL)
       {
          printf("\nError opening input file");
          return 1;
       }
       outf=fopen("/home/abhishek/Desktop/reverse.txt","w");
       if(outf==NULL)
       {
          printf("\nError opening output file");
          return 1;
       }
       
        while(flag==0)
       {
          for(x=0;x<200;x++)
          {
    	 if((ch=fgetc(inf))!=EOF)
    	   {
    		temp[x]=ch;
    		lol=x;
               }		
    	 else
    	    flag=1;
          }
          for(x=lol;x>=0;x--)
    	 fputc(temp[x],outf); 
       }
       
       printf("\nDone!");
       return 0;
    }
    The code in blue is causing all the problems. First it was printing absurd characters like squares and upside down question marks, but then I fixed it to print only those characters which are in the file. But still I'm not getting the output I was expecting.

    shakespear.txt
    Welcome to the Web's first edition of the Complete Works of William Shakespeare. This site has offered Shakespeare's plays and poetry to the Internet community since 1993.

    Consider that you have an array of 5 characters in size. The user enter 10 characters! That means 10 characters + 1 (for the ending '\0') is written to your array. But your array is only 5 chars long! Uh-oh!
    What can happen? Well, the result is undefined. Basically that means the result is not defined. Defined as in that we know the behavior. In undefined, we cannot guarantee what will happen.
    First and foremost - it's a security risk. Lots of malware and other security threats take advantage of buffer overruns to run malicious code.

    reverse.txt

    evah uoy taht redisnoC

    .3991 ecnis ytinummoc tenretnI eht ot yrteop dna syalp s'eraepsekahS dereffo sah etis sihT .eraepsekahS mailliW fo skroW etelpmoC eht fo noitide tsrif s'beW eht ot emocleW neppah nac tahW
    !ho-hU !gnol srahc 5 ylno si yarra ruoy tuB .yarra ruoy ot nettirw si )'0\' gnidne eht rof( 1 + sretcarahc 01 snaem tahT !sretcarahc 01 retne resu ehT .ezis ni sretcarahc 5 fo yarra na s'ti - tsomerof dna tsriF
    .neppah lliw tahw eetnaraug tonnac ew ,denifednu nI .roivaheb eht wonk ew taht ni sa denifeD .denifed ton si tluser eht snaem taht yllacisaB .denifednu si tluser eht ,lleW ?.edoc suoicilam nur ot snurrevo reffub fo egatnavda ekat staerht ytiruces rehto dna erawlam fo stoL .ksir ytiruces a
    The output is all scattered
    What's wrong?

  2. #2
    Registered User
    Join Date
    Apr 2008
    Posts
    396
    I'm not sure the output is 'wrong':

    your code read the 1st 200 characters, then dump them reversed, resume by reading the next 200 characters, dump them reversed, and so on...

    You should rather change the algorithm.
    Last edited by root4; 05-20-2008 at 01:51 PM.

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Do you want to print the entire file backwards, or each line in correct order, but the text reversed, or something else?

    If you want to print a line at a time backwards, then you need to stop your loop when you reach a newline.

    If you want to print the entire file backwards (and not rely on some arbitrary limit of the size of your arrays, the computers memory or some such), you need to start from the very end of the file (one byte from the end of file) [use fseek to position the file pointer], read one char, output it to the outfile, then move to the previous character (which means move "relative -2", since the read moved forward one char), read & output and go on like that until you have reached file-position 0.

    You can use a similar approach but read more than one char at a time, which would have the slight benefit of being a bit faster [particularly on large files, using a block size of say 4KB (4096) would help a fair bit]. But it also makes the logic a bit more complicated.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  4. #4
    Super unModrator
    Join Date
    Dec 2007
    Posts
    321
    Thanks for the replies. I had never used fseek before but after reading this I modified the code:
    Code:
    #include<stdio.h>
    int main()
    {
          char temp[200],ch;
          int x,lol,count=0;
          int flag=0;
          FILE *inf,*outf;
          inf=fopen("/home/abhishek/Desktop/shakespear.txt","r");
          if(inf==NULL)
         {
                printf("\nError opening input file");
                return 1;
          }
          outf=fopen("/home/abhishek/Desktop/reverse.txt","w");
          if(outf==NULL)
          {
                 printf("\nError opening output file");
                 return 1;
           }
      /*   
           while(flag==0)
          {
                for(x=0;x<200;x++)
               {
    	          if((ch=fgetc(inf))!=EOF)
    	         {
    		       temp[x]=ch;
    		       lol=x;
                     }		
    	         else
    	                flag=1;
                 }
                for(x=lol;x>=0;x--)
    	         fputc(temp[x],outf); 
           }*/
            while(fgetc(inf)!=EOF)
                 count++;
            fseek(inf,0,SEEK_END);
            while(flag==0)
            {
                   for(x=0;x<200;x++)
                  {
    	            if((ch=fgetc(inf))!=EOF)
    	           {
    	                  temp[x]=ch;
    	                 fseek(inf,-1,SEEK_CUR);
    	            }
    	           else
    	                 flag=1;
                    }
                   for(x=0;x<200 && x<=count;x++);
                   {
    	            fputc(temp[x],outf);
                    }
             }
       
             fclose(inf);
             fclose(outf); 
             printf("\nDone!");
             return 0;
     }
    It compiles and runs, but when I try to open the output file (I clicked ok and it opened a blank Kwrite)
    Last edited by abh!shek; 05-20-2008 at 09:05 PM.

  5. #5
    Super unModrator
    Join Date
    Dec 2007
    Posts
    321
    Am I using fseek correctly......or not?

  6. #6
    The larch
    Join Date
    May 2006
    Posts
    3,573
    It doesn't look right. If you first seek to the end, you probably can't input anything (other than EOF). It is also probably not enough to seek -1 from current, because when you read a character the file pointer advances one character.

    The inner loop currently just complicates it. You are still reading and writing one character at a time, not many as suggested, so you might just read one character and write it to the other file etc.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  7. #7
    Banned
    Join Date
    Nov 2007
    Posts
    678
    Just start reading from the end of file (no EOF though), and, every time you read a char move file position backwards by two. Simple.

  8. #8
    Super unModrator
    Join Date
    Dec 2007
    Posts
    321

    Talking Whhhooooooooooohoooooooooooooooooo

    This works

    Code:
    #include<stdio.h> 
    
    int main()
    {
    	char ch;
    	int max=0,count=0;
    	FILE *inf,*outf;
    	inf=fopen("/home/abhishek/Desktop/shakespear.txt","r");
    	if(inf==NULL)
    	{
    		printf("\nError opening input file");
    		return 1;
    	}
    	outf=fopen("/home/abhishek/Desktop/reverse.txt","w");
    	if(outf==NULL)
    	{
    		printf("\nError opening output file");
    		return 1;
    	}
    	/* 
            while(flag==0)
    	{
    		for(x=0;x<200;x++)
    		{
    			if((ch=fgetc(inf))!=EOF)
    			{
    				temp[x]=ch;
    				lol=x;
    			}
    			else flag=1;
    		}
    		for(x=lol;x>=0;x--) fputc(temp[x],outf);
    	}
    	*/
            while(fgetc(inf)!=EOF) 
                     max++;
    	
            /* fseek(inf,-1,SEEK_END);
    	while(flag==0)
    	{
    		for(x=0;x<200;x++)
    		{
    			if((ch=fgetc(inf))!=EOF)
    			{
    				temp[x]=ch;
    				fseek(inf,-2,SEEK_CUR);
    			}
    			else
    			{
    				flag=1;
    				break;
    			}
    		}
    		for(x=0;x<200 && x<=count;x++);
    
    		{
    			fputc(temp[x],outf);
    		}
    	}
    	*/
            fseek(inf,-1,SEEK_END);
    	while(count<=max)
    	{
    		ch=fgetc(inf);
    		printf("\n&#37;d characters copied",count);
    		count++;
    		fputc(ch,outf);
    		fseek(inf,-2,SEEK_CUR);
    	}
    	fclose(inf);
    	fclose(outf);
    	printf("\nDone!");
    	return 0;
    }
    But I still want to make it more efficient, as matsp said. I will have to read more about fread, fwrite, fgets, fputs. Any other comments on the above code are always welcome.

  9. #9
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    There is a function "ftell()" that gives you the current location in the file. That, immediately after your "fseek(... -1, SEEK_END)" could easily replace your loop counting the number of chars in the file. That would take away roughly a third of the time your program takes, since it will only need to read the input file once, instead of twice.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  10. #10
    Super unModrator
    Join Date
    Dec 2007
    Posts
    321
    yeah thanks. Now I have another crazy idea in my mind -- I will reverse and mp3 and play it backwards. That would be funny

  11. #11
    The larch
    Join Date
    May 2006
    Posts
    3,573
    However, I don't think reversing the bytes in the file is going to achieve this...
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  12. #12
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by anon View Post
    However, I don't think reversing the bytes in the file is going to achieve this...
    I don't think so either - in fact I'm fairly confident that at least some parts of an MP3 contains order-dependent data.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  13. #13
    Super unModrator
    Join Date
    Dec 2007
    Posts
    321
    So is it IM-Possible? I've seen video clips and sounds being played in reverse :-/

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    It is possible, but you must keep the codec algorithm in mind.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    Super unModrator
    Join Date
    Dec 2007
    Posts
    321
    Apparently too hard for me then. I'll do something else now.

    *Reversing an mp3 idea dumped*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. To find the memory leaks without using any tools
    By asadullah in forum C Programming
    Replies: 2
    Last Post: 05-12-2008, 07:54 AM
  2. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  3. Need Help Fixing My C Program. Deals with File I/O
    By Matus in forum C Programming
    Replies: 7
    Last Post: 04-29-2008, 07:51 PM
  4. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM
  5. My program, anyhelp
    By @licomb in forum C Programming
    Replies: 14
    Last Post: 08-14-2001, 10:04 PM