This blog is under construction

Friday 27 April 2012

ungetc example in C

Header file:
    stdio.h

Synopsis:
     int ungetc(int ch, FILE *stream);

Description:
     It pushes character ch back onto the given stream.  Returns character ch on success, EOF on failure.


ungetc function C example:


  #include<stdio.h>
  #include<string.h>
  int main() {
        char str[100], ch;
        FILE *fp;
        int i = 0;
        fp = fopen("mastering-c.txt", "r");
        if (fp == NULL) {
                printf("Error in opening the file\n");
                return;
        }
        while ((ch = getc(fp)) != EOF)  {
                if (i < 10)
                        ungetc('#', fp);  // pushing '#' back to the stream fp
                putchar(ch);
                i++;
        }
        fclose(fp);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/cpgms/exp$ cat mastering-c.txt
  Hello world
  This is puts example program in C
  Thanks for visiting our blog
  jp@jp-VirtualBox:~/cpgms/exp$ gcc ungetc.c
  jp@jp-VirtualBox:~/cpgms/exp$ ./a.out
  H##########ello world
  This is puts example program in C
  Thanks for visiting our blog



No comments:

Post a Comment