Thread: file writing crashes

  1. #16
    Unregistered
    Guest
    nope

    adsl;kfj ;lkjasdf l;akjasdflkajdf ;lkjadsflkajdsf lakjasdf lkjadf ;lkaj flkajfd

    adsflkjadflkjadf
    adlsfkjadflkjadf
    asdlfkjadflkjadfj
    adlfjkadfjf
    ^Z
    output of text file:

    adsl;kfj ;lkjasdf l;akjasdflkajdf ;lkjadsflkajdsf lakjasdf lkjadf ;lkaj flkajfd

  2. #17
    Unregistered
    Guest

    yeap

    got it.. i commented the fclose(fp) .. i didn't notice this before

    Code:
    #include <stdio.h> 
    
    int main(void) 
    { 
    
    	FILE *fp; 
    	char buf[80]; 
    	fp = fopen("some.txt", "w"); 
    	if ( fp != NULL ) 
    	{ 
    		/* ** Read until the user hits CTRL+D or CTRL+Z */ 
    		while ( fgets(buf, 80, stdin) != NULL ) 
    		{
    			fputs(buf, fp); 
    			//fclose(fp);
    		} 
    	}
    
    	return 0; 
    }
    can you please tell me what these two things mean ?

    if ( fp != NULL )

    fgets(buf, 80, stdin) != NULL

  3. #18
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >can you please tell me what these two things mean ?
    fopen returns NULL if the file could not be opened, you should check for this because if the file wasn't opened you will have problems writing to it. As for fgets:
    /* ISO C Standard */
    The fgets function returns s if successful. If end-of-file is encountered and no
    characters have been read into the array, the contents of the array remain unchanged and a
    null pointer is returned. If a read error occurs during the operation, the array contents are
    indeterminate and a null pointer is returned.
    Translation: Check for fgets returning NULL because problems can occur if you don't.

    -Prelude
    My best code is written with the delete key.

  4. #19
    Registered User moonwalker's Avatar
    Join Date
    Jul 2002
    Posts
    282

    hmm

    this is my first time playing with files...
    i changed it to this:
    Code:
    #include <stdio.h> 
    
    int main(void) 
    { 
    
    	FILE *fp; 
    	char buf[1]; 
    	fp = fopen("some.txt", "w"); 
    	if ( fp != NULL ) 
    	{ 
    		/* ** Read until the user hits CTRL+D or CTRL+Z */ 
    		while ( fgets(buf, 2, stdin) != NULL ) 
    		{
    			fputs(buf, fp); 
    			//fclose(fp);
    		} 
    
    	}
    
    	return 0; 
    }
    I reduced the buffer size to 1..And it worked pretty good.

    what i didn't understand is..
    let's say i typed "a" and didn't press enter.. what does fgets return in the while loop? "a" ? then does fputs immediately
    store it in fp... i.e. file ?

    to check this, i typed "a", did not press enter, and checked ... some.txt was 0 bytes.. i pressed enter... it was still zero bytes..
    it kept saying 0 bytes until i pressed ^Z

    so where is the typed matter going all this time ? into the memory ?

    also, what is the right place to put fclose(fp) in this code... doesn't
    it exit immediately when anyone presses ^Z ?

    but when there's no fclose(fp) in the program, how come it saved
    it all up after ^Z ?
    Last edited by moonwalker; 08-12-2002 at 11:37 AM.

  5. #20
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > I reduced the buffer size to 1..And it worked pretty good
    You're lucky it worked at all

    char buf[1];
    fgets(buf, 2, stdin)

    That extra byte which fgets will write is going into the great unknown.

    > let's say i typed "a" and didn't press enter
    Until you press enter, the text is being buffered by the operating system (and/or the C library). When you press enter, the text is chopped up into sizeof(buff)-1 blocks and returned to your code in successive calls to fgets()

    > so where is the typed matter going all this time ? into the memory ?
    Yes - output files are also buffered
    If you want to see data in your file immediately, then use fflush()

    > but when there's no fclose(fp) in the program, how come it saved
    A well behaved C runtime will close all open files when you exit the program normally. If on the other hand your program were to crash at this time, you would probably lose.

    Code:
    #include <stdio.h>
    
    int main ( void ) {
        char    buff[5];
        FILE    *fp;
    
        fp = fopen( "test.txt", "w" );
        if ( fp == NULL ) {
            perror( "Unable to open" );
            return 1;
        }
    
        while ( fgets( buff, sizeof(buff), stdin ) != NULL ) {
            printf( "Processing line `%s`\n", buff );
            fputs( buff, fp );
            fflush( fp );   // if you really want to see each fputs in the file
        }
    
        fclose( fp );       // close the file
        clearerr( stdin );  // clear the EOF state on stdin
        return 0;
    }
    And this is what it looks like when you run the code
    Code:
    the quick brown fox jumps over the lazy dog
    Processing line `the `
    Processing line `quic`
    Processing line `k br`
    Processing line `own `
    Processing line `fox `
    Processing line `jump`
    Processing line `s ov`
    Processing line `er t`
    Processing line `he l`
    Processing line `azy `
    Processing line `dog
    `
    a man a plan a canal panama
    Processing line `a ma`
    Processing line `n a `
    Processing line `plan`
    Processing line ` a c`
    Processing line `anal`
    Processing line ` pan`
    Processing line `ama
    `
    ^Z

  6. #21
    Registered User moonwalker's Avatar
    Join Date
    Jul 2002
    Posts
    282

    thanks

    thanks, that cleared most of it..

    but..

    so far, what i understood is: please correct me if i am wrong..


    1) fgets(buf, num, stdin) ... takes input from stdin, num-1
    characters at a time and puts it in buff array only after
    the user presses enter..

    then why does it still retain if i type 10 characters and press an
    enter after that when the buff is only 5 char long ?

    2) i am sorry, i still didn't get this returning NULL thing, i read
    the same thing in 5 different ways but it still didn't make sense.

    while ( fgets( buff, sizeof(buff), stdin ) != NULL )
    what does this exactly mean?


    thanks for your time.

  7. #22
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > then why does it still retain if i type 10 characters and press an
    > enter after that when the buff is only 5 char long ?
    Study the output of my program

    A single call to fgets() results in a single call to the environment to read a line up to the next newline.

    However, if this line does not fit in the supplied buffer (you type in 10 chars, and there's only room for 5), then the next call to fgets() will see that there is more data (chars 5..10) and return those immediately (without calling the environment).

    This repeats until there is no more data, and fgets once again calls the environment for the next line.

    > while ( fgets( buff, sizeof(buff), stdin ) != NULL )
    > what does this exactly mean?
    fgets returns NULL when EOF is detected on the input stream (in this case, stdin)

  8. #23
    Registered User moonwalker's Avatar
    Join Date
    Jul 2002
    Posts
    282

    thanks... and..

    >A single call to fgets() results in a single call to the environment to read a line up to the next newline.

    does this mean that the buffer can be as small as buf[2] ?
    so keeping the buffer size high doesn't do much to this particular
    program ?

  9. #24
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > does this mean that the buffer can be as small as buf[2] ?
    Yes.

    But this doesn't control the size of the buffer which is used between fgets and the environment. In DOS for example, this is fixed at 128 bytes (when reading from stdin). Other OS's and stream types have different limits.

    > so keeping the buffer size high doesn't do much to this particular program ?
    Well if you choose a 'large' size, like BUFSIZ defined in stdio.h, you will have far fewer calls to each function (fewer=better), since each line will typically fit in one buffer rather than the 10 or so in my previous example.

  10. #25
    Registered User moonwalker's Avatar
    Join Date
    Jul 2002
    Posts
    282

    and..

    I just changed the buffer size to 2.
    I typed 5 characters, went back using arrowkeys and changed
    the first character and pressed enter...the program looked
    like it went into an infinite loop... ?
    the same thing happened even after i used backspace.

    when does EOF occur in fgets() ?

    >the next call to fgets() will see that there is more data (chars 5..10) and return those immediately (without calling the environment).

    fgets() will be called only after we press enter right ? so if
    i dont press enter and keep on typing for a while (like 20 characters) and then press enter, it keeps returning sets of
    2 characters after that ?

  11. #26
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >when does EOF occur in fgets() ?
    When the end of file marker is reached for a file or the user types something along the lines of CTRL+D or CTRL+Z.

    >it keeps returning sets of2 characters after that ?
    Yes and no, it will return two characters but one of those characters is a string terminating nul. So it will appear as if only one character is processed. Run this to see it in action:
    Code:
    #include <stdio.h>
    
    int main ( void )
    {
      char buff[2];
    
      while ( fgets( buff, sizeof(buff), stdin ) != NULL ) {
        printf ( "Processing line `%s`\n", buff );
        fflush ( stdout );
      }
      return 0;
    }
    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 09:35 AM
  2. Trouble writing to file using fwrite()
    By yougene in forum C Programming
    Replies: 4
    Last Post: 12-30-2008, 05:13 PM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  4. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM
  5. Writing input from a file into shared memory
    By RazielX in forum C Programming
    Replies: 2
    Last Post: 09-23-2004, 12:34 PM