4

by this

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

i get to know that in linux directories and files are considered to be file. so when i give any directory-path or file-path in fopen with read mode it doesnt give NULL file descriptor and?

so how can i check that whether it is dirctory path or file-path ? if i am getting some path from command argument?

Community
  • 1
  • 1
Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222
  • usually files have extension, i.e. "*.txt", "*.log", therefore, based on that, you can know if it's a file or directory, but wait for a better answer –  Dec 08 '11 at 07:12
  • Similar or same questions already asked. See http://stackoverflow.com/questions/1036625/differentiate-between-a-unix-directory-and-file-in-c and http://stackoverflow.com/questions/146924/how-can-i-tell-if-a-given-path-is-a-directory-or-a-file-c-c – hrishikeshp19 Dec 08 '11 at 07:25
  • 1
    @DorinDuminica: In UNIX contexts, it is considered bad style to rely on suffixes to identify anything. First consider the file attributes (like the file type in this case), then try `file` to identify the file, and only fall back on extensions if nothing else works. – thiton Dec 08 '11 at 07:54

3 Answers3

6

man 2 stat:

NAME
     fstat, fstat64, lstat, lstat64, stat, stat64 -- get file status

...

     struct stat {
         dev_t           st_dev;           /* ID of device containing file */
         mode_t          st_mode;          /* Mode of file (see below) */

...

     The status information word st_mode has the following bits:

...

     #define        S_IFDIR  0040000  /* directory */
zed_0xff
  • 32,417
  • 7
  • 53
  • 72
2

You can use S_ISDIR macro .

Community
  • 1
  • 1
Igor
  • 26,650
  • 27
  • 89
  • 114
2

thanks zed_0xff and lgor Oks

this things can be check by this sample code

#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

its null
directory
Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222