#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    2
    Rep Power
    0

    Undefined ungetc behavior


    hi!

    i'm new at c so i'm trying to understnad something. here it is:

    main.c:

    Code:
    #include <stdio.h>
    
    int main(void)
    {
          FILE *fp;
    
          fp = fopen("test.txt", "r+");
    
          putchar(fgetc(fp));
          putchar(fgetc(fp));
          putchar(fgetc(fp));
          //putchar(fgetc(fp));
          
          ungetc('t', fp);
          ungetc('U', fp);
          ungetc('P', fp);
          
          putchar('\n');
          putchar(fgetc(fp));
          putchar(fgetc(fp));
          putchar(fgetc(fp));
    }
    test.txt:
    Code:
    gET
    outputs as:
    Code:
    gET
    PUt
    i'm using fgetc to make sure the file position gets increment once evry call :p .

    but when i uncomment the 4th putchar(fgetc(fp)), the output become like this:

    Code:
    gET
    t
    it's like after EOF was reached, we can effectiively call ungetc only once. that's it... i thoght you can do it at least 3 times, like what happened before we uncommented the putchar(fgetc(fp)).

    why???
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,387
    Rep Power
    1871
    Originally Posted by man page
    DESCRIPTION
    ungetc() pushes c back to stream, cast to unsigned char, where it is available for subsequent read operations. Pushed-back characters will be returned in reverse
    order; only one pushback is guaranteed.

    RETURN VALUE
    ungetc() returns c on success, or EOF on error.
    When you put the input stream into an EOF condition with the 4th fgetc, then you can only expect one pushback to work.
    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
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    2
    Rep Power
    0
    uhhh.. :( i guess this is sumthing that i cant do anything about...

IMN logo majestic logo threadwatch logo seochat tools logo