Sunday, 11 March 2018

c - Why does fopen("any_path_name",'r') not give NULL as return?



While debugging some code I got something like below:



#include


int main()
{
FILE *fb = fopen("/home/jeegar/","r");
if(NULL == fb)
printf("it is null");
else
printf("working");
}



Here in fopen I gave a somewhat valid path name but not a filename. Shouldn't fopen return NULL then? But it does not return null!



Edit:



If I give path of valid directory in fopen then it will print working:



If I give path of invalid directory in fopen then it will print it is null



Edit:

spec says



Upon successful completion, fopen() shall return a pointer to the object 
controlling the stream. Otherwise, a null pointer shall be returned.


so here whether error code set or not, it MUST return NULL



And error code setting is an extansion to ISO C standard standard.




ERROR IS ALSO NOT GOING TO SET HERE



#include
#include

int main()
{
errno = 0;
FILE *fb = fopen("/home/jeegar/","r");
if(fb==NULL)

printf("its null");
else
printf("working");


printf("Error %d \n", errno);


}



OUTPUT IS



workingError 0 

Answer



I think that in Unix everything (directories included) is considered to be file so fopen should work on them.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...