Angelo
Angelo

Reputation: 153

C open() directory no error

I have a function that opens file then read theses files, with the standard open() et read() functions. I use the errno variables for all possible errors such as permission denied or no such file or directory, but when I use open on a directory it don't return a error it simply open it and try to read it. So how can I get an error message when I give open a directory ?

Upvotes: 1

Views: 2106

Answers (3)

Angelo
Angelo

Reputation: 153

I don't wanted to use anything else as read and write, I found that the error is returned at using read() not by open()

Upvotes: 1

Jesse Chen
Jesse Chen

Reputation: 529

Directory also a file in Unix*, if you want to avoid to open a directory by open(), you may need to check the file type. As @nayabbashasayed say,you can use the stat to check the file type and more info.

Here is an example code to check the type by stat:

const char  *filePath;
struct stat  fileStatBuf;
if(stat(filePath,&fileStatBuf) == -1){
     perror("stat");
     exit(1);
}

/*
 *You can use switch to check all
 *the types you want, now i just use 
 *if to check one.
*/
if((fileStatBuf.st_mode & S_IFMT) == S_IFDIR){
    printf("This type is directory\n");
}

Hope that can help you.

Upvotes: 1

NayabSD
NayabSD

Reputation: 1120

Directory is also a file (In terms of Unix/Linux). So generally you won't get an error. You can use stat or fstat function for tracking of ordinary or special files.

When you use either stat or fstat, you need to declare a struct stat variable like struct stat var. The stat structure has a member called st_mode which has the information of what kind of file it is.

struct stat {
    dev_t     st_dev;     /* ID of device containing file */
    ino_t     st_ino;     /* inode number */
    mode_t    st_mode;    /* protection */
    nlink_t   st_nlink;   /* number of hard links */
    uid_t     st_uid;     /* user ID of owner */
    gid_t     st_gid;     /* group ID of owner */
    dev_t     st_rdev;    /* device ID (if special file) */
    off_t     st_size;    /* total size, in bytes */
    blksize_t st_blksize; /* blocksize for file system I/O */
    blkcnt_t  st_blocks;  /* number of 512B blocks allocated */
    time_t    st_atime;   /* time of last access */
    time_t    st_mtime;   /* time of last modification */
    time_t    st_ctime;   /* time of last status change */
};

Upvotes: 2

Related Questions