C Program I/O File reversal

  • (2 Pages)
  • +
  • 1
  • 2

17 Replies - 1292 Views - Last Post: 09 March 2010 - 12:07 PM Rate Topic: -----

#1 Guest_DamienCurr*


Reputation:

C Program I/O File reversal

Posted 06 March 2010 - 01:08 PM

Help.

I'm having difficulty trying to solve this programming issue I've been battling for the past four days. I've been to the forums, searched the web and read all of the related class materials (twice). Whatever I try does not seem to work.

I need an example of a C program that opens a text file, loads the content into a buffer, reverses the text in the buffer and then uses that data to overwrite the file. When you open the file, everything is backwards.

I'm using this to open the file I've selected:


fp = fopen(filename, "r");




I'm using this to allocate the space needed in the buffer and read the text into the buffer:


char *buffer = malloc(20000);
        char buf[20000];
        
        n = fread(buffer, 20000, 1, fp);
        n = strlen(buffer);






I'm using this to reverse the string:


for ( ; n>=0 ;n--)
        {
         if ( (c=*(buffer+n)) !='\0'  )
         {
          buf[i++]= c ;
         }
        }




I'm using this to close the file:


fclose(fp);




The way I have it now, the reversed text is displayed on the screen, but does not overwrite the file with the reversed text and save it. I tried something else that only ended up deleting everything in the text file.

Any assistance/direction would be greatly appreciated...

Thanks!

Is This A Good Question/Topic? 0

Replies To: C Program I/O File reversal

#2 Martyn.Rae  Icon User is offline

  • The programming dinosaur
  • member icon

Reputation: 540
  • View blog
  • Posts: 1,406
  • Joined: 22-August 09

Re: C Program I/O File reversal

Posted 06 March 2010 - 01:12 PM

What you need to do is add the following code after the fclose you currently have.

    fp = fopen(filename, "w+");
    n = fwrite(buffer, n, 1, fp);
    fclose(fp);



job done!

This post has been edited by Martyn.Rae: 06 March 2010 - 01:17 PM

Was This Post Helpful? 0
  • +
  • -

#3 Guest_Nerran_*


Reputation:

Re: C Program I/O File reversal

Posted 06 March 2010 - 01:16 PM

Well you forgot to write data =)
You'll need fwrite(buf,20000,sizeof(buf),fp);
Place it after the for loop.
Was This Post Helpful? 1

#4 Martyn.Rae  Icon User is offline

  • The programming dinosaur
  • member icon

Reputation: 540
  • View blog
  • Posts: 1,406
  • Joined: 22-August 09

Re: C Program I/O File reversal

Posted 06 March 2010 - 01:18 PM

Thank you Nerran, I have modified my code accordingly.
Was This Post Helpful? 0
  • +
  • -

#5 DamienCurr  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 69
  • Joined: 03-May 09

Re: C Program I/O File reversal

Posted 06 March 2010 - 01:46 PM

Thanks to everyone who responded in my time of need! :bigsmile:

Here is what I have now:


else if (option == 4)
      {
       fp = fopen(filename, "r");     //open file
       if((fp == NULL))
       {
        printf("No file was selected!\n");
        exit(1);       
       }
              
        char *buffer = malloc(20000);
        char buf[20000];
        
        n = fread(buffer, 20000, 1, fp);
        n = strlen(buffer);
        printf("buffer :%s == %d\n"  ,buffer,n);

        for ( ; n>=0 ;n--)
        {
         if ( (c=*(buffer+n)) !='\0'  )
         {
          buf[i++]= c;
         }
         fwrite(buf,20000,sizeof(buf),fp);
        }
        printf("reversed contents :%s\n" , buf);
              
       fclose(fp);                    //close file
       
       fp = fopen(filename, "w+"); 
       n = fwrite(buffer, n, 1, fp); 
       fclose(fp);
      }



However, everytime I try to run it, the program crashes. Anything look out of place to you?

Enternal thanks!
Was This Post Helpful? 0
  • +
  • -

#6 Munawwar  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 162
  • View blog
  • Posts: 457
  • Joined: 20-January 10

Re: C Program I/O File reversal

Posted 06 March 2010 - 02:20 PM

for ( ; n>=0 ;n--) //The for loop ends when n=-1
{
   if ( (c=*(buffer+n)) !='\0'  )
   {
      buf[i++]= c;  //I hope you initailized i=0 before the loop
   }
   fwrite(buf,20000,sizeof(buf),fp);
}


Your fwrite here is causing you trouble.You don't need this here since you are writing to the file at the end of your program :
fp = fopen(filename, "w+"); 
n = fwrite(buffer, n, 1, fp); //logical error
fclose(fp);



Now, There are two logical errors here. When the for loop ends, what do you think the value of 'n' will be? -1 rit? n = fwrite(buffer, n, 1, fp); is wrong then.
Second mistake is that you are writing buffer to the file when you need to write buf to the file.
So it should be: n = fwrite(buf, strlen(buf), 1, fp);

Now lets go back to your for loop where you wrote :
if ( (c=*(buffer+n)) !='\0' )
This is false only when n=strlen(buffer). If you assign n=strlen(buffer)-1, then you don't need this line. [And even if it was needed I would prefer writing it as : if ( (c=buffer[n]) !='\0' ) :)]

This post has been edited by Munawwar: 06 March 2010 - 02:20 PM

Was This Post Helpful? 0
  • +
  • -

#7 DamienCurr  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 69
  • Joined: 03-May 09

Re: C Program I/O File reversal

Posted 06 March 2010 - 03:24 PM

Munawwar,

Thank you very much for the corrections. The program works great, now. One thing, though. I noticed as I was selecting different text files to test, when I dispayed a file's content, there were "left overs" from the previous file, in addition to what was added from the currently viewed file. I take it the buffer needs cleaning out before it accepts anything new? Do I use "fflush" or something else?

Thanks!
Was This Post Helpful? 0
  • +
  • -

#8 eker676  Icon User is offline

  • Software Engineer
  • member icon

Reputation: 378
  • View blog
  • Posts: 1,833
  • Joined: 18-April 09

Re: C Program I/O File reversal

Posted 06 March 2010 - 03:48 PM

Use a single 'w' for your file parameters when you are opening it.

Using 'w+' will append to the file. 'w' overwrites the file.
Was This Post Helpful? 0
  • +
  • -

#9 DamienCurr  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 69
  • Joined: 03-May 09

Re: C Program I/O File reversal

Posted 06 March 2010 - 04:28 PM

eker676,

Thank you very much for your input. I tried removing the "+", but the file continued to behave the same way. I deleted the .exe file and re-compiled. No change.

Thanks!
Was This Post Helpful? 0
  • +
  • -

#10 eker676  Icon User is offline

  • Software Engineer
  • member icon

Reputation: 378
  • View blog
  • Posts: 1,833
  • Joined: 18-April 09

Re: C Program I/O File reversal

Posted 06 March 2010 - 04:39 PM

Could you post your code again?
Was This Post Helpful? 0
  • +
  • -

#11 DamienCurr  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 69
  • Joined: 03-May 09

Re: C Program I/O File reversal

Posted 06 March 2010 - 07:33 PM

Sure! Here it is:


  //Reverse file
      else if (option == 4)
      {
       fp = fopen(filename, "r");             //open file
       if((fp == NULL))
       {
        printf("No file was selected!\n");
        exit(1);       
       }              
        char *buffer = malloc(20000);         //allocate memory
        char buf[20000];
        
        n = fread(buffer, 20000, 1, fp);
        n = strlen(buffer) -1;

        for ( ; n>=0 ;n--)
        {
         if ( (c = *(buffer+n)) !='\0'  )
         {
          buf[i++] = c;
         }
         fwrite(buf, 20000, sizeof(buf), fp);
        }             
       fclose(fp);                            //close file
       
       fp = fopen(filename, "w+"); 
       n = fwrite(buf, strlen(buf), 1, fp); 
       fclose(fp);
      }



Was This Post Helpful? 0
  • +
  • -

#12 eker676  Icon User is offline

  • Software Engineer
  • member icon

Reputation: 378
  • View blog
  • Posts: 1,833
  • Joined: 18-April 09

Re: C Program I/O File reversal

Posted 06 March 2010 - 07:51 PM

I see the problem.

You are trying to read and write to a file simultaneously when you declared the file stream as read-only.

Try this: It reads the file, closes the stream, then overwrites the file with the buffer.
This may or may not work, I haven't compiled it.

 //Reverse file
      else if (option == 4)
      {
       fp = fopen(filename, "r");             //open file
       if((fp == NULL))
       {
        printf("No file was selected!\n");
        exit(1);       
       }              
        char *buffer = malloc(20000);         //allocate memory
        char buf[20000];
        
        // read the file
        n = fread(buffer, 20000, 1, fp);
        n = strlen(buffer) -1;

        fclose(fp);
        
        // opens the same file but deletes all the data
        fp = fopen(filename, "w");
        for ( ; n>=0 ;n--)
        {
         if ( (c = *(buffer+n)) !='\0'  )
         {
          buf[i++] = c;
         }
         fwrite(buf, 20000, sizeof(buf), fp);
        }             
       fclose(fp);   //close file      
      }

This post has been edited by eker676: 06 March 2010 - 07:52 PM

Was This Post Helpful? 0
  • +
  • -

#13 DamienCurr  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 69
  • Joined: 03-May 09

Re: C Program I/O File reversal

Posted 06 March 2010 - 08:10 PM

Good evening and thanks for the post! I tried your suggestion. The file compiled, but the program crashed everytime I tried Option #4. When I went and opened up the text file, it was empty except for a period.
Was This Post Helpful? 0
  • +
  • -

#14 eker676  Icon User is offline

  • Software Engineer
  • member icon

Reputation: 378
  • View blog
  • Posts: 1,833
  • Joined: 18-April 09

Re: C Program I/O File reversal

Posted 06 March 2010 - 09:03 PM

Okay, I'm no expert with C file IO but this stood out after reexamination:
fwrite(buf, 20000, sizeof(buf), fp);


Note the second parameter 20000. The second parameter is the size of one element from the array. In this case it should be:
fwrite(buf, 1, sizeof(buf), fp);


Try changing that.

Also, move that fwrite function out of the for loop to just before you close the file.

If that doesn't work, post your entire code.

This post has been edited by eker676: 06 March 2010 - 09:04 PM

Was This Post Helpful? 0
  • +
  • -

#15 DamienCurr  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 69
  • Joined: 03-May 09

Re: C Program I/O File reversal

Posted 06 March 2010 - 09:23 PM

Well, I tried your suggestions and the test file displayed garbage characters. Here's the code:


#include <stdio.h>
#include<string.h>

int option;                     //for option selection
int result;                     //variable used in option 3
int n = 0;                      //variable used in option 4
int i = 0;                      //variable used in option 4
char filename[50] = "";         //used for file to be manipulated
char newfilename[50] = "";      //used to rename file in option 3
char line[255];                 //variable used in option 2
char *buffer;                   //variable used in option 4
char c;                         //variable used in option 4
FILE *fp;                    

main()
{
 do
 {     
      printf("\n");
      printf("File Manipulation Program\n");
      printf("=========================\n");
      printf("\n");
      printf("Please choose from the following options: \n\n");
      printf("0 - Exit the program\n");
      printf("1 - Select file to manipulate\n");
      printf("2 - Display file contents\n");
      printf("3 - Rename the file selected\n");
      printf("4 - Reverse file contents\n");
      printf("\n");
      printf("Select Option: ");
      scanf("%d", &option);
      printf("\n\n");
      
      //user selects file
      if (option == 1)
      {
       printf("Name of your File: ");
       scanf("%s", filename);   
      }
      //Display contents of file
      else if (option == 2)
      {
       printf("File contents are: \n\n %s", filename);
       
       fp = fopen(filename, "r");
       if((fp == NULL))
       {       
       printf("No file was selected!\n");
       exit(1);       
       }
       while(!feof(fp))
        {
        if(fgets(line, 255, fp))
        printf("%s", line);               
        }
        printf("\n\nEnd of file: \n");
        fclose(fp);    
      }
      
      //Rename file
      else if (option == 3)
      {
      if((fp == NULL))
       {
        printf("No file was selected!\n");
        exit(1);       
       }           
       printf("The current name of the file is: %s", filename);
       printf("\nRename your file as: ");
       scanf("%s", newfilename);
       result = rename(filename, newfilename);
      }
      
      //Reverse file
      else if (option == 4)
      {
       fp = fopen(filename, "r");             //open file
       if((fp == NULL))
       {
        printf("No file was selected!\n");
        exit(1);       
       }              
        char *buffer = malloc(20000);         //allocate memory
        char buf[20000];
        
        n = fread(buffer, 20000, 1, fp);
        n = strlen(buffer) -1;

        for ( ; n>=0 ;n--)
        {
         if ( (c = *(buffer+n)) !='\0'  )
         {
          buf[i++] = c;
         }
         fwrite(buf, 20000, sizeof(buf), fp);
        }             
       fclose(fp);                            //close file
       
       fp = fopen(filename, "w+"); 
       n = fwrite(buf, strlen(buf), 1, fp); 
       fclose(fp);
      }
  }
 while(option !=0);

return 0;

}






Thanks for looking it over!
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2