Bill asked:
> Is this the way to use perror and clearerr ?

Try this instead:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  FILE *fp;

  fp = fopen("nonexistent.file", "r");
  if (fp == NULL)
  {
    perror("Unable to open file");
    exit(EXIT_FAILURE);
  }

  /* (Read the file here) */

  fclose(fp);
  exit(EXIT_SUCCESS);
}

This will print something like "Unable to open file: No such 
file or directory" on stderr.

> if((fp=fopen("data","wb"))==NULL {
> perror("fopen");
> clearerr("fopen");
> exit(EXIT_FAILURE);
> }

No: clearerr() is expecting a FILE * pointer, i.e. fp in 
this case, whereas "fopen" is effectively a char * pointer 
pointing to the string literal "fopen". You want 
clearerr(fp).

But clearerr(fp) won't work in this context because it's 
clearerr(NULL), which will crash the program (seg fault). 
You can't use clearerr(fp) or fclose(fp) etc unless you've 
successfully opened the stream first! This is why it's 
necessary to test for fp == NULL and avoid using fp if true.

David

Reply via email to