Thread: read and write to file

  1. #1
    Registered User
    Join Date
    Aug 2004
    Posts
    22

    read and write to file

    Code:
     /*very very simple encrytion*/
    fp=fopen("message.txt","r+");
    do
    {
        c=fgetc(fp);
        xy=(c+1)%256;
        fputc(xy, fp);
    }while(c!=EOF);
    fclose(fp);
    Im trying to read from a file and then shift it by +1 and write to the same file again.
    but it wont work. I donīt get any error.

    example: message.txt
    hello what is your name bla bla bla

    I get:
    an empty file
    Last edited by staticalloc; 09-16-2004 at 07:49 AM.

  2. #2
    former member Brain Cell's Avatar
    Join Date
    Feb 2004
    Posts
    472
    I don't get what you're trying to do within the program but you are using the wrong mode to open the file. You used "w" wich is for creating a file with the name "message.txt" or overwriting it if it already exist. (w = write)

    You should use the mode "r+" to read from an existing file and write to it (update it).
    Last edited by Brain Cell; 09-16-2004 at 07:45 AM.
    My Tutorials :
    - Bad programming practices in : C
    - C\C++ Tips
    (constrcutive criticism is very welcome)


    - Brain Cell

  3. #3
    Registered User
    Join Date
    Aug 2004
    Posts
    22
    well now the file didnīt change at all after "r+"

    Im trying a simple file encryption.
    I

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Code:
    int ch;
    while ( (ch=fgetc(fp)) != EOF ) {
        xy=(ch+1)%256;
        fseek( fp, -1, SEEK_CUR );  // step back a char
        fputc(xy, fp);
    }
    Never use do while to read a file - it doesn't handle empty files
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    ---
    Join Date
    May 2004
    Posts
    1,379
    you cant read and write to the same file without closing the file first and re-opening it with a different attribute.
    best to have an input file and then an output file.

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by sand_man
    you cant read and write to the same file without closing the file first and re-opening it with a different attribute.
    best to have an input file and then an output file.
    Bet me.

    man 3 fopen
    DESCRIPTION

    The fopen function opens the file whose name is the string
    pointed to by path and associates a stream with it.

    The argument mode points to a string beginning with one of
    the following sequences (Additional characters may follow
    these sequences.):

    r Open text file for reading. The stream is posi-
    tioned at the beginning of the file.

    r+ Open for reading and writing. The stream is posi-
    tioned at the beginning of the file.

    w Truncate file to zero length or create text file
    for writing. The stream is positioned at the
    beginning of the file.

    w+ Open for reading and writing. The file is created
    if it does not exist, otherwise it is truncated.
    The stream is positioned at the beginning of the
    file.

    a Open for writing. The file is created if it does
    not exist. The stream is positioned at the end of
    the file.

    a+ Open for reading and writing. The file is created
    if it does not exist. The stream is positioned at
    the end of the file.
    All you had to do was read up on fopen to see that.

    Quzah.
    Hope is the first step on the road to disappointment.

  7. #7
    Registered User
    Join Date
    Aug 2004
    Posts
    22
    well I still canīt see why this programm wont work


    Code:
    #include <stdio.h>
    #include <stdlib.h.>
    
    
    FILE *fp;
    
    int main (void)
    {
        int code, key, xy,  c;
    	printf("Enter  1 OR -1:");
    	scanf("%d",&code);
    	printf("\nEnter Key-->");
    	scanf("%d",&key);
    
    	fp=fopen("message.txt","r");   /*read file, show on screen*/
    	if(fp==NULL)
    	{
    		printf("\nFile does not exist\n");
    		exit(EXIT_FAILURE);
        }
    	else
    	{
    		do
    		{
    			c=fgetc(fp);
    			putchar(c);
    		}while(c!=EOF);
        }
    	printf("\n");
        fclose(fp);
    
    	fp=fopen("message.txt","r+");   /*read file and write encrypted file*/
    	do
        {
    	   c=fgetc(fp);
    	   xy=(c+key*code)%256;
    	   fputc(xy, fp);
        }while(c!=EOF);
    	fclose(fp);
        return 0;
    }

    I replaced Salems code
    Code:
    int ch;
    while ( (ch=fgetc(fp)) != EOF ) {
        xy=(ch+1)%256;
        fseek( fp, -1, SEEK_CUR );  // step back a char
        fputc(xy, fp);
    }
    and I get an endless loop which made the opened file really big

  8. #8
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    I found a thread with posting on a similar topic here. I think the upshot was to do something like this.
    Code:
    #include <stdio.h>
    #include <limits.h>
    
    int main (void)
    {
       int ch, key = 1;
       const char filename[] = "file.txt";
       FILE *file = fopen(filename, "r+b");
       if ( file )
       {
          while ( (ch = fgetc(file)) != EOF )
          {
             int xy = (ch + key) % UCHAR_MAX;
             fseek(file, -1, SEEK_CUR);
             fputc(xy, file);
             fflush(file);
             fseek(file, 0, SEEK_CUR);
          }
          fclose(file);
       }
       return 0;
    }
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  9. #9
    Registered User
    Join Date
    Aug 2004
    Posts
    22
    thanks to everyone for your reply, but this is still really frustrating. I dont get any error nor warnings. Whats wrong with my algorithm?

  10. #10
    ---
    Join Date
    May 2004
    Posts
    1,379
    Quote Originally Posted by quzah
    Bet me.
    All you had to do was read up on fopen to see that.

    Quzah.
    I seem to be wrong a lot dont I?
    I guess I'm learning something new everyday.

  11. #11
    former member Brain Cell's Avatar
    Join Date
    Feb 2004
    Posts
    472
    i didn't read the modified code but i noticed that you commited the same error again when opening the stream at the line :
    Code:
    fp=fopen("message.txt","r");   /*read file, show on screen*/
    you opened it with a "read only" mode then you tried to write to the stream with :
    Code:
    fputc(xy, fp);
    use the "r+" mode to read AND write.
    My Tutorials :
    - Bad programming practices in : C
    - C\C++ Tips
    (constrcutive criticism is very welcome)


    - Brain Cell

  12. #12
    Registered User
    Join Date
    Mar 2004
    Posts
    536
    Quote Originally Posted by staticalloc
    thanks to everyone for your reply, but this is still really frustrating. I dont get any error nor warnings. Whats wrong with my algorithm?
    Just because you don't get "any error nor warnings", there's no guarantee that the program performs as you intended.

    Salem's fix made the program work "OK" with my Windows XP gcc compiler, but not with Borland bcc32 or with Visual C++.

    Dave_Sinkula's solution worked with all compilers (actually we don't need the fflush(), but the second fseek() is required).


    Here's a passage from The Standard C Library by P. J. Plauger, copyright 1992, based on the 1998 ISO C standard:

    When a file is opened with update mode, both input and output may be performed on the associated stream. However, output may not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input may not be directly followed by output without an intervening call to a file positioning function...
    So, it turns out that my gcc doesn't require the extra fseek(), but bcc32 and Visual C++ do, consistent with the above quote.

    By the way, if you want to do error checking on fseek(), note that its returned value is zero for success and non-zero for failure.

    I hadn't run across this in my own work, because I always create a new file for writing (therefore saving the original file unchanged). If it is required for the modified file to have the same name as the original, the files can be renamed by the program after they are closed.

    Regards,

    Dave
    Last edited by Dave Evans; 09-17-2004 at 08:21 AM.

  13. #13
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by sand_man
    I seem to be wrong a lot dont I?
    It happens to all of us now and again.
    Quote Originally Posted by sand_man
    I guess I'm learning something new everyday.
    That's the important thing.

    Quzah.
    Hope is the first step on the road to disappointment.

  14. #14
    Registered User caroundw5h's Avatar
    Join Date
    Oct 2003
    Posts
    751
    I'm just now starting to learn files and it seems You might also want to make sure you close the file properly.
    Code:
    if( fclose(file) == 0)
      
           printf("whatever you want here");
           
        else
        	puts("CLOSING FILE FAILED!!");
    
        return 0;
    fclose returns a value of 0 if succesful and EOF if not. Anything can happen. ex: disk is full, diskette removed
    or even an i/o error.

    edit: thanks for those links you posted quazah. They seem to include some details my book failed to mention.
    Warning: Opinions subject to change without notice

    The C Library Reference Guide
    Understand the fundamentals
    Then have some more fun

  15. #15
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >You might also want to make sure you close the file properly.
    It certainly couldn't hurt if you really need robust code or if you don't flush the stream before closing it and a write error occurs. At that point you're looking at a loss of data situation, and recovery is critical. For toy programs like we write here, you just need to think of a call to fclose as a placeholder for something more solid.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 04:27 PM
  2. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  3. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  4. SYnchronize read & write of a cache file
    By lei_michelle in forum C Programming
    Replies: 4
    Last Post: 02-26-2008, 05:49 PM
  5. Replies: 3
    Last Post: 03-04-2005, 02:46 PM