This blog is under construction

Saturday 28 April 2012

clearerr example in C

Header file:
    stdio.h

Synopsis:
     void clearerr(FILE *stream);

Description:
     It clears the EOF and error indicators for stream.


clearerr function C example:


  #include<stdio.h>
  #include<string.h>
  #include<errno.h>
  int main() {
        FILE *fp;
        int ret, flag = 1;
        char ch, *str;
        fp = fopen("input.txt", "r");
        if (fp == NULL) {
                str = strerror(errno);
                perror(str);
                return;
        }

        fputc('a', fp);  // trying to write in a file which is opened in read mode
        ret = ferror(fp);  // sets error indicator
        if (ret) {
                printf("Tried to write in a file opened in read mode\n");
        }
        ch = fgetc(fp);
        while(!feof(fp)) {
                ret = ferror(fp);
                if (ret) {
                        printf("\nError indicator not cleared..\n");
                        printf("Clearing error indicator\n");
                        clearerr(fp);  // clear error indicator for fp stream
                } else if (ret) {
                        printf("Trying to write in file opened in read mode\n");
                }
                printf("%c", ch);
                ch = fgetc(fp);
        }

        fclose(fp);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/cpgms/exp$ ls
  a.out  input.txt

  jp@jp-VirtualBox:~/cpgms/exp$ cat input.txt 
  hello world
  hello world
  hello world

  jp@jp-VirtualBox:~/cpgms/exp$ ./a.out
  Tried to write in a file opened in read mode

  Error indicator not cleared..
  Clearing error indicator
  hello world
  hello world
  hello world



No comments:

Post a Comment