This blog is under construction

Saturday, 28 April 2012

ferror example in C

Header file:
    stdio.h

Synopsis:
     int ferror(FILE *stream);

Description:
     Returns 0, if there's no error. Non-zero is returned if there's any error indicator.


ferror function C example:


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

        fputc('a', fp);
        ret = ferror(fp);
        if (ret) {
                printf("Tried to write in a file which is opened in read mode\n");
        }
        fclose(fp);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/cpgms/exp$ ./a.out
  Tried to write in a file which is opened in read mode
  jp@jp-VirtualBox:~/cpgms/exp$ cat ferror.txt
  Sample program for ferror
  1st open file in read mode
  Try to write in it
  ferror returns non-zero value
  since we are trying to write in a file which is opened in read mode




No comments:

Post a Comment