Dec
14

Why fopen() doesn’t get fail by passing directory name in argument?

Author JIGAR PATEL    Category c, linux, Tips, tips     Tags

Once i have made one small application where i was passing full file name as command line argument in my application where i am going to fopen() that file BUT once i have just passed any directory name instad of file name still my fopen() does not get fails…!!

#include<stdio.h>
#include <errno.h>
 
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

here fb is not going null and also not getting any error..


after some research i came to know that in

“In Linux everything (directories included) is considered to be file”

so opening any directory in read mode is not getting fail but if you open directory in write mode then fopen will get fail.

So now Question comes :

how can we check that fopen() has opened that is file or directory?

here is some code which shows you trick for checking that things

#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main()
{
struct stat statbuf;
 
FILE *fb = fopen("/home/jeegar/","r");
if(fb==NULL)
    printf("its null\n");
else
    printf("not null\n");
 
stat("/home/jeegar/", &statbuf);
 
if(S_ISDIR(statbuf.st_mode))
    printf("directory\n");
else
    printf("file\n");
return 0;
}

Output is

 not null
directory
 

JIGAR PATEL

hey I am an Artist who love to write code…! Well I am an EC graduate From Ganpat University and now i am working as Embedded software engineer in one private firm.. find me at here JigAr Patel

More PostsWebsiteTwitterFacebook

You may like to read this also....

1 Comment to “Why fopen() doesn’t get fail by passing directory name in argument?”

  • Sandra January 14, 2012 at 3:49 pm

    Like the blog

Post comment

*

CommentLuv badge
Follow us on Twitter! Follow us on Twitter!

Search in this website

our sponsors

latest comments

Find us on Facebook

Top Authors

35 posts
saurabh
22 posts
10 posts

Find us on stackoverflow

Polls

Tell us who you are

View Results

Loading ... Loading ...

My Bookmarks

Sponsers Link