C fopen errno is not set

406 Views Asked by At

I am using IAR embedded workbench for programming. I have eval board which supports microSD memory card. I have all the libraries and the application is working. I tried to access a file which does not exists in sd card to simulate failure and capture any file open error.

#include <errno.h>
#include <string.h>
int IsFileExists(const char* filename) {
  errno = 0;
  FILE* fptr = fopen(filename, "r");
  printf("Error:%d %s",errno,strerror(errno))
  if (fptr != NULL) {    
    fclose(fptr);
    return 1;
  }
  return 0;
}

The fptr is NULL and errno is 0 always. Why the errno is not set to non-zero value?

Thanks!

2

There are 2 best solutions below

5
On

You must declare errorno as extern value. and you have no need to set errorno as 0. It automatically sets after run fopen function. Refer: https://www.tutorialspoint.com/cprogramming/c_error_handling.htm

0
On

C99-7.19.5.3(8) says nothing about errno at fopen() return. Some other functions are required to set errno (C99-7.19.9.3 fsetpos() for instance). So it seems it is not required for fopen.

What OS are you using ?