POSIX:sys/stat
lastmod 2018-08-17created 2016-05-0510 edits
Methods
int chmod(const char *, mode_t);
int fchmod(int, mode_t);
int fstat(int, struct stat *);
int lstat(const char *, struct stat *);
int mkdir(const char *, mode_t);
int mkfifo(const char *, mode_t);
int mknod(const char *, mode_t, dev_t);
int stat(const char *, struct stat *);
mode_t umask(mode_t);
check macros
-
S_ISDIR: directory -
S_ISREG: regular file -
S_ISCHR: character device -
S_ISBLK: block device -
S_ISFIFO: FIFO -
S_ISLNK: symbolic link -
S_ISSOCK: socket
Directory exists
#include <sys/stat.h>
struct stat sb;
if (stat(pathname, &sb) == 0 && S_ISDIR(sb.st_mode))
{
...it is a directory...
}
Windows & MinGW version
- Stackoverflow: Error: identifier “_S_IFDIR” is undefined
- MSDN: _stat structure st_mode field constants
-
_S_IFMT: file type mask -
_S_IFDIR: directory -
_S_IFCHR: character special (indicates a device if set) -
_S_IFREG: regular -
_S_IREAD: read permission, owner -
_S_IWRITE: write permission, owner -
_S_IEXEC: execute/search permission, owner
mode_t
sys/stat.h provides you with several integers you can bytewise-OR (|) together to create your mode_t:
- User: S_IRUSR (read), S_IWUSR (write), S_IXUSR (execute)
- Group: S_IRGRP (read), S_IWGRP (write), S_IXGRP (execute)
- Others: S_IROTH (read), S_IWOTH (write), S_IXOTH (execute)
Additionally, some shortcuts are provided (basically a bitwise-OR combination of the above
- Read + Write + Execute: S_IRWXU (User), S_IRWXG (Group), S_IRWXO (Others)
- DEFFILEMODE: Equivalent of 0666 = rw-rw-rw-
- ACCESSPERMS: Equivalent of 0777 = rwxrwxrwx Therefore, to give only the user rwx (read+write+execute) rights whereas group members and others may not do anything, you can use any of the following mkdir() calls equivalently:
In order to give anyone any rights (mode 0777 = rwxrwxrwx), you can use any of the following calls equivalently:
mkdir("mydir", S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH);
mkdir("mydir", S_IRWXU | S_IRWXG | S_IRWXO);
mkdir("mydir", ACCESSPERMS);
Favorite site
- stat(2) - Linux man page
- The Single UNIX ® Specification, Version 2 - sys/stat.h
- GNU libc: 14.9.3 Testing the Type of a File
- [Recommended] Getting file status information - stat, fstat, and lstat Functions 1
- C language system programming: files and directories
Source code
References
-
System_section_-_file_stat_functions.pdf ↩
Pages that link here