File and Directory Attributes in UNIX/Linux
Every file and directory in a UNIX system has associated metadata that describes its properties. These attributes are maintained by the kernel and are used for access control, storage management, ownership, and file operations.
Learning Objectives
- Understand file attributes.
- Learn file metadata.
- Understand UNIX file types.
- Learn the purpose of inodes.
- Understand directory attributes.
- Prepare for file attribute system calls.
1. What is a File?
In UNIX, a file is a named collection of data stored on a storage device. The operating system treats many different resources, including ordinary files, directories, devices, and communication endpoints, as files.
Applications access files through standard system interfaces without requiring knowledge of the underlying storage implementation.
2. What are File Attributes?
File attributes are pieces of information maintained by the operating system that describe the characteristics of a file. These attributes are collectively known as metadata because they describe the file rather than its contents.
3. Why are File Attributes Important?
- Determine file permissions.
- Identify file ownership.
- Store timestamps.
- Determine file type.
- Support file security.
- Assist file-system management.
4. File Contents vs File Attributes
| File Contents | File Attributes |
|---|---|
| Actual stored data | Information describing the file |
| Read by applications | Managed by the operating system |
| May contain text, images, or binary data | Includes permissions, owner, size, timestamps, and file type |
5. File Metadata
Metadata is information about a file rather than the data stored within the file. Examples include:
- Owner
- Group
- Permissions
- File size
- Creation and modification times (where supported)
- Access time
- File type
6. Introduction to Inodes
UNIX file systems store file metadata in a data structure known as an inode. An inode contains information describing a file but does not store the file name itself.
7. File Name and Inode Relationship
Directories map file names to inode numbers. The inode then references the file's metadata and data blocks.
8. UNIX File Types
| File Type | Description |
|---|---|
| Regular File | Stores user data |
| Directory | Stores file name mappings |
| Character Device | Provides byte-oriented device access |
| Block Device | Provides block-oriented device access |
| FIFO | Named pipe for interprocess communication |
| Symbolic Link | References another file path |
| Socket | Communication endpoint |
9. Directory Attributes
Directories also possess file attributes because, in UNIX, directories are a special type of file. Their metadata includes ownership, permissions, timestamps, size, and file type, just like regular files.
10. Interview Questions
- What is a file in UNIX?
- What are file attributes?
- What is metadata?
- Why are file attributes important?
- What is an inode?
- Does an inode contain the file name?
- How does a directory locate a file?
- Name the major UNIX file types.
- Why is a directory considered a file?
- What is the difference between file contents and file metadata?
11. stat()
The stat() function retrieves the attributes of a file
identified by its pathname.
The operating system fills a struct stat structure with the
file's metadata.
12. Parameters and Return Value of stat()
| Parameter | Description |
|---|---|
| pathname | Path of the file whose attributes are to be obtained |
| buf | Pointer to a struct stat that receives the file attributes |
On success, stat() returns 0.
On failure, it returns -1 and sets errno.
13. Example: Using stat()
14. fstat()
The fstat() function retrieves file attributes using an already opened file descriptor instead of a pathname.
15. Example: Using fstat()
16. lstat()
The lstat() function is similar to
stat(), except that when the specified pathname refers to a
symbolic link, it returns information about the symbolic link itself
rather than the file to which the link refers.
17. stat() vs lstat()
| stat() | lstat() |
|---|---|
| Follows symbolic links | Does not follow symbolic links |
| Returns attributes of the target file | Returns attributes of the symbolic link itself |
| Commonly used for normal file access | Useful when examining symbolic links |
18. stat() vs fstat()
| stat() | fstat() |
|---|---|
| Uses a pathname | Uses a file descriptor |
| File may not already be open | File must already be open |
| Suitable for pathname-based access | Suitable for descriptor-based access |
19. File Attribute Retrieval Flow
20. Interview Questions
- What is the purpose of
stat()? - What information does
struct statcontain? - What is the difference between
stat()andfstat()? - What is the difference between
stat()andlstat()? - When should
fstat()be used? - Why does
stat()require a pathname? - What does
lstat()return for a symbolic link?
21. struct stat
The struct stat structure stores the metadata returned
by stat(), fstat(), and
lstat().
Each member provides information describing a particular attribute of
the file.
22. Common Members of struct stat
| Member | Description |
|---|---|
| st_mode | File type and permission bits |
| st_ino | Inode number |
| st_dev | Device containing the file |
| st_nlink | Number of hard links |
| st_uid | User ID of file owner |
| st_gid | Group ID of file owner |
| st_size | File size in bytes |
| st_atime | Last access time |
| st_mtime | Last modification time |
| st_ctime | Last status change time |
23. Visual Representation of struct stat
24. File Type Macros
The file type is encoded within the
st_mode member.
UNIX provides standard macros to determine the file type.
25. Common File Type Macros
| Macro | Checks For |
|---|---|
| S_ISREG(mode) | Regular file |
| S_ISDIR(mode) | Directory |
| S_ISCHR(mode) | Character device |
| S_ISBLK(mode) | Block device |
| S_ISFIFO(mode) | FIFO (named pipe) |
| S_ISLNK(mode) | Symbolic link |
| S_ISSOCK(mode) | Socket |
26. Example: Determining File Type
27. File Type Detection Flow
28. Why Use File Type Macros?
The file type information is stored as encoded bits within
st_mode.
The standard macros decode these bits in a portable manner, allowing
applications to determine the file type without depending on
implementation-specific bit values.
29. File Type Summary
| File Type | Macro |
|---|---|
| Regular File | S_ISREG() |
| Directory | S_ISDIR() |
| Character Device | S_ISCHR() |
| Block Device | S_ISBLK() |
| FIFO | S_ISFIFO() |
| Symbolic Link | S_ISLNK() |
| Socket | S_ISSOCK() |
30. Interview Questions
- What is the purpose of
struct stat? - Which member stores the inode number?
- Which member stores the file size?
- Which member contains the file type information?
- How can a program determine whether a file is a directory?
- What is the purpose of
S_ISREG()? - Why should applications use file type macros instead of checking bit values directly?
31. File Permission Bits
The st_mode member of
struct stat contains not only the file type but also the
file permission bits.
These permission bits determine the operations that different users are
allowed to perform on the file.
32. Permission Categories
UNIX divides file permissions into three categories of users.
| Category | Description |
|---|---|
| Owner (User) | The user who owns the file. |
| Group | Users belonging to the file's group. |
| Others | All remaining users. |
33. Permission Types
| Permission | Meaning |
|---|---|
| Read (r) | Permission to read the file. |
| Write (w) | Permission to modify the file. |
| Execute (x) | Permission to execute the file as a program. |
34. Permission Layout
Each permission category has three permission bits: read, write, and execute.
35. Permission Bit Macros
| Macro | Description |
|---|---|
| S_IRUSR | Owner read permission |
| S_IWUSR | Owner write permission |
| S_IXUSR | Owner execute permission |
| S_IRGRP | Group read permission |
| S_IWGRP | Group write permission |
| S_IXGRP | Group execute permission |
| S_IROTH | Others read permission |
| S_IWOTH | Others write permission |
| S_IXOTH | Others execute permission |
36. Example: Checking Owner Read Permission
37. Example: Checking Multiple Permissions
38. Permission Interpretation
39. Permission Summary
| Permission | Owner | Group | Others |
|---|---|---|---|
| Read | S_IRUSR | S_IRGRP | S_IROTH |
| Write | S_IWUSR | S_IWGRP | S_IWOTH |
| Execute | S_IXUSR | S_IXGRP | S_IXOTH |
40. Interview Questions
- Which member of
struct statstores the permission bits? - How many permission categories exist in UNIX?
- What are the three basic file permissions?
- What does
S_IRUSRrepresent? - How can a program determine whether the owner has write permission?
- What is the purpose of
S_IXGRP? - Why are permission bits stored together with file type information in
st_mode?
41. chmod()
The chmod() system call changes the access permission bits of an existing file or directory. Only the file owner (or a privileged process) is permitted to modify these permission bits.
42. Parameters and Return Value of chmod()
| Parameter | Description |
|---|---|
| pathname | Path of the file or directory |
| mode | New permission bits to be assigned |
Returns 0 on success.
Returns -1 on failure and sets
errno.
43. Example: Using chmod()
The permission value 0644 grants:
- Owner: Read and Write
- Group: Read
- Others: Read
44. fchmod()
The fchmod() function changes file permissions using an already opened file descriptor instead of a pathname.
45. Example: Using fchmod()
This example assigns read and write permissions only to the owner.
46. Symbolic vs Octal Permissions
| Octal | Symbolic | Description |
|---|---|---|
| 0777 | rwxrwxrwx | Full permissions |
| 0755 | rwxr-xr-x | Typical executable file |
| 0644 | rw-r--r-- | Typical text file |
| 0600 | rw------- | Private file |
| 0400 | r-------- | Read-only for owner |
47. Permission Change Flow
48. When to Use chmod() and fchmod()
| Function | Typical Use |
|---|---|
chmod() |
When the file is identified by its pathname. |
fchmod() |
When an open file descriptor is already available. |
49. Common Errors While Changing Permissions
| Error | Possible Cause |
|---|---|
| ENOENT | Specified pathname does not exist. |
| EACCES | Permission denied while accessing the pathname. |
| EPERM | Process is not permitted to change the file mode. |
| EBADF | Invalid file descriptor passed to fchmod(). |
50. Interview Questions
- What is the purpose of
chmod()? - What is the difference between
chmod()andfchmod()? - Who is allowed to change file permissions?
- What does the permission value
0644represent? - When should
fchmod()be preferred overchmod()? - What does the kernel update when
chmod()succeeds? - What happens if an invalid file descriptor is passed to
fchmod()?
51. umask()
The umask() function sets the file mode creation mask for the calling process. The mask specifies which permission bits should be cleared when new files or directories are created.
52. How umask() Works
When a process creates a new file or directory, it requests a set of permission bits. Before assigning these permissions, the kernel removes the permission bits specified by the process's file mode creation mask.
53. Example: Using umask()
The requested mode is 0666.
With a mask of 022, the resulting file permissions become
0644.
54. Relationship Between creat(), open(), and umask()
| Function | Role |
|---|---|
creat() |
Creates a new file with requested permissions. |
open() with O_CREAT |
Creates a file if it does not already exist. |
umask() |
Restricts the permissions assigned during file creation. |
55. chown()
The chown() function changes the ownership of a file by specifying a new user ID and group ID.
56. fchown()
The fchown() function performs the same operation as
chown(), but it identifies the file using an open file
descriptor instead of a pathname.
57. Example: Using chown()
This example attempts to change the owner and group of
sample.txt.
58. File Ownership
Every UNIX file has an associated owner and group.
These values are stored in the st_uid and
st_gid members of struct stat.
| Member | Description |
|---|---|
| st_uid | User ID of the file owner |
| st_gid | Group ID of the file owner |
59. Ownership Change Flow
60. Interview Questions
- What is the purpose of
umask()? - How does
umask()affect newly created files? - Why does
umask()not modify existing file permissions? - What is the relationship between
open(),creat(), andumask()? - What is the purpose of
chown()? - What is the difference between
chown()andfchown()? - Which members of
struct statstore file ownership information?
61. access()
The access() function checks whether the calling process
can access a file using its real user ID and
real group ID.
Unlike functions such as open(), it does not use the
effective user ID when performing permission checks.
62. Access Modes
| Mode | Description |
|---|---|
| F_OK | Check whether the file exists. |
| R_OK | Check read permission. |
| W_OK | Check write permission. |
| X_OK | Check execute permission. |
63. Example: Using access()
64. Real User ID vs Effective User ID
| Real User ID | Effective User ID |
|---|---|
| Identifies the actual user who started the process. | Determines the permissions currently used by the process. |
Used by access(). |
Used by most file-related system calls such as open(). |
| Normally remains unchanged. | May change for set-user-ID programs. |
65. faccessat() (POSIX Extension)
POSIX Extension:
The faccessat() function extends the capabilities of
access() by allowing permission checks relative to a
directory file descriptor and supporting additional flags.
It is part of newer POSIX standards and is not covered in older editions
of APUE.
66. File Timestamps
UNIX maintains several timestamps for every file to record different
types of file activity.
These values are stored in struct stat.
67. Timestamp Members
| Member | Description |
|---|---|
| st_atime | Time of last file access. |
| st_mtime | Time of last file content modification. |
| st_ctime | Time of last file status change (metadata change). |
Note: The st_ctime field records the last
status change (such as permission or ownership changes). It does
not represent the file creation time in traditional
UNIX file systems.
68. Timestamp Update Flow
69. Example: Displaying File Attributes
70. Interview Questions
- What is the purpose of
access()? - Which IDs are used by
access()for permission checking? - How does
access()differ fromopen()? - What is the difference between the real user ID and the effective user ID?
- What do
F_OK,R_OK,W_OK, andX_OKrepresent? - What does
st_atimerecord? - What is the difference between
st_mtimeandst_ctime? - Does
st_ctimerepresent the file creation time?
71. Useful Linux Commands
| Command | Purpose |
|---|---|
ls -l |
Display file permissions, owner, group, and size. |
stat filename |
Display complete file metadata. |
chmod 755 filename |
Change file permissions. |
chown user:group filename |
Change file ownership. |
umask |
Display the current file creation mask. |
umask 022 |
Set a new file creation mask. |
72. Best Practices
- Always check the return values of file attribute system calls.
- Use
stat()when working with file pathnames. - Use
fstat()when a file descriptor is already available. - Use
lstat()when information about a symbolic link itself is required. - Apply the principle of least privilege when assigning file permissions.
- Set an appropriate
umask()before creating files. - Use the standard POSIX permission and file type macros instead of hard-coded bit values.
73. Common Programming Mistakes
| Mistake | Possible Result |
|---|---|
Ignoring the return value of stat() |
Using uninitialized metadata |
Using stat() instead of lstat() for symbolic links |
Incorrect information about the link |
Assuming st_ctime is the file creation time |
Incorrect interpretation of metadata |
Using overly permissive modes such as 0777 |
Reduced system security |
Forgetting the effect of umask() during file creation |
Unexpected file permissions |
| Testing file type by hard-coded bit patterns | Reduced portability |
74. File Attribute API Summary
| API | Primary Purpose |
|---|---|
stat() |
Retrieve file attributes using a pathname. |
fstat() |
Retrieve file attributes using a file descriptor. |
lstat() |
Retrieve attributes of a symbolic link. |
chmod() |
Change file permissions. |
fchmod() |
Change permissions using a file descriptor. |
umask() |
Set the file mode creation mask. |
chown() |
Change file ownership. |
fchown() |
Change ownership using a file descriptor. |
access() |
Check file accessibility using the real user ID. |
75. File Attribute Workflow
77. Advanced Interview Questions
- Explain the relationship between directories, file names, inodes, and data blocks.
- Differentiate
stat(),fstat(), andlstat(). - Why is
st_modedivided into file type bits and permission bits? - Explain how
umask()affects file creation. - Why should
S_ISREG()be used instead of checking bit patterns directly? - Compare
chmod()withfchmod(). - Compare
chown()withfchown(). - Why does
access()use the real user ID? - Explain the purpose of
st_atime,st_mtime, andst_ctime. - Describe a complete workflow for securely creating and configuring a new file.
Concept Mastery Assessment — Module 23
Verify your conceptual understanding with 12 targeted technical assessment questions. Instant feedback and explanations are provided for every choice.