w3resource

C clearerr() function

C library function - clearerr()

The clearerr() function is used to clear the end-of-file and error indicators for the stream to which stream points.

Syntax:

void clearerr(FILE *stream)

clearerr() Parameters:

Name Description Required /Optional
stream Identifies an address for a file descriptor, which is an area of memory associated with an input or output stream. Required

Return value from clearerr()

  • The clearerr() function shall not return a value.

Example: clearerr() function

The following program opens an existing file called test.txt for reading. As the file opens in reading mode so it will not allow to write anything in it, so when fputc() function try to write some text ferror() function will display an error message. This error, however, is cleared using the clearerr() function. Therefore, the next time the ferror() function performs an error check, it displays that no errors have been detected.

#include <stdio.h>

int main ()
{
  FILE * fp;
  fp = fopen("test.txt","r");

  if (fp == NULL) perror ("Error opening file.");
  else {
    fputc('abcd', fp);

    if(ferror(fp)) 
    {
      printf("Error writing to test.txt.\n");
      clearerr(fp);
    }

    fgetc(fp);

    if (!ferror(fp))
      printf("No error reading test.txt.\n"); 

    fclose(fp);
  }

  return 0;
}

Output:

Error writing to test.txt.
No error reading test.txt.

Assuming we have a text file file.txt, which is an empty file, let us compile and run the above program, this will produce the following result because we try to read a file which we opened in write only mode.

C Programming Code Editor:

Previous C Programming: C fclose()
Next C Programming: C feof()



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

Returning an array using C

You can't return arrays from functions in C. You also can't (shouldn't) do this:

char *returnArray(char array []){
 char returned [10];
 //methods to pull values from array, interpret them, and then create new array
 return &(returned[0]); //is this correct?
} 

returned is created with automatic storage duration and references to it will become invalid once it leaves its declaring scope, i.e., when the function returns.

You will need to dynamically allocate the memory inside of the function or fill a preallocated buffer provided by the caller.

Dynamically allocate the memory inside of the function (caller responsible for deallocating ret)

char *foo(int count) {
    char *ret = malloc(count);
    if(!ret)
        return NULL;

    for(int i = 0; i < count; ++i) 
        ret[i] = i;

    return ret;
}

Call it like so:

int main() {
    char *p = foo(10);
    if(p) {
        // do stuff with p
        free(p);
    }

    return 0;
}

Ref : https://bit.ly/3yFIeao





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook