I'm trying to understand the flags for the st_mode field of the stat structure of that stat command, but I'm having such a hard time! I found this example here, but I really don't understand this code fragment:
if ( mode & S_IRUSR ) str[1] = 'r'; /* 3 bits for user */
if ( mode & S_IWUSR ) str[2] = 'w';
if ( mode & S_IXUSR ) str[3] = 'x';
if ( mode & S_IRGRP ) str[4] = 'r'; /* 3 bits for group */
if ( mode & S_IWGRP ) str[5] = 'w';
if ( mode & S_IXGRP ) str[6] = 'x';
if ( mode & S_IROTH ) str[7] = 'r'; /* 3 bits for other */
if ( mode & S_IWOTH ) str[8] = 'w';
if ( mode & S_IXOTH ) str[9] = 'x';
I know that "&" is the bitwise AND operator, but nothing else. I don't even know what to ask.
PD: Sorry about the previous questions I asked. I don't know how to mark a question answered or anything like that :(
st_mode This field contains the file type and mode. See inode(7) for further information. st_nlink This field contains the number of hard links to the file. st_uid This field contains the user ID of the owner of the file.
The stat() system call returns data on the size and parameters associated with a file. The call is issued by the ls -l command and other similar functions. The data required to satisfy the stat() system call is contained in the inode.
The stat() function gets status information about a specified file and places it in the area of memory pointed to by the buf argument. If the named file is a symbolic link, stat() resolves the symbolic link. It also returns information about the resulting file.
The st_size field gives the size of the file (if it is a regular file or a symbolic link) in bytes. The size of a symbolic link is the length of the pathname it contains, without a terminating null byte. The st_blocks field indicates the number of blocks allocated to the file, 512-byte units.
mode is a bitfield which is a common way to pack data. Think of each bit in the field as being a toggle switch which can be set to off or on. To check if the toggle is on, you check to see if the appropriate bit has been set using the & operator. You can set bits using | and clear them using ~ bitwise operations.
Well, the POSIX spec for <sys/stat.h>
enumerates everything you can learn from the st_mode field of struct stat
.
Is your question "What can this field tell me", or is it "How do I extract the information", or both?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With