ADVERTISEMENT
Responsive Ad Unit • Systems Architecture & Low-Level Engineering

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

Directory ↓ File Name ↓ Inode Number ↓ Inode ↓ File Data Blocks

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

  1. What is a file in UNIX?
  2. What are file attributes?
  3. What is metadata?
  4. Why are file attributes important?
  5. What is an inode?
  6. Does an inode contain the file name?
  7. How does a directory locate a file?
  8. Name the major UNIX file types.
  9. Why is a directory considered a file?
  10. 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.

#include <sys/stat.h> int stat( const char *pathname, struct stat *buf );

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()

#include <stdio.h> #include <sys/stat.h> int main() { struct stat info; if (stat("sample.txt", &info) == 0) { printf("File Size: %ld\n", (long)info.st_size); } return 0; }

14. fstat()

The fstat() function retrieves file attributes using an already opened file descriptor instead of a pathname.

#include <sys/stat.h> int fstat( int fd, struct stat *buf );

15. Example: Using fstat()

#include <fcntl.h> #include <sys/stat.h> int fd; struct stat info; fd = open("sample.txt", O_RDONLY); fstat(fd, &info);

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.

#include <sys/stat.h> int lstat( const char *pathname, struct stat *buf );

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

Application ↓ stat() or fstat() or lstat() ↓ Kernel ↓ Read File Metadata ↓ Fill struct stat ↓ Return to Application

20. Interview Questions

  1. What is the purpose of stat()?
  2. What information does struct stat contain?
  3. What is the difference between stat() and fstat()?
  4. What is the difference between stat() and lstat()?
  5. When should fstat() be used?
  6. Why does stat() require a pathname?
  7. 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.

#include <sys/stat.h> struct stat;

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

struct stat ├── st_mode ├── st_ino ├── st_dev ├── st_nlink ├── st_uid ├── st_gid ├── st_size ├── st_atime ├── st_mtime └── st_ctime

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

struct stat info; stat("sample.txt", &info); if (S_ISREG(info.st_mode)) { printf("Regular File\n"); } if (S_ISDIR(info.st_mode)) { printf("Directory\n"); }

27. File Type Detection Flow

stat() ↓ struct stat ↓ st_mode ↓ S_ISREG() S_ISDIR() S_ISCHR() ... ↓ File Type Identified

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

  1. What is the purpose of struct stat?
  2. Which member stores the inode number?
  3. Which member stores the file size?
  4. Which member contains the file type information?
  5. How can a program determine whether a file is a directory?
  6. What is the purpose of S_ISREG()?
  7. 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

Owner r w x ↓ Group r w x ↓ Others r w x

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

struct stat info; stat("sample.txt", &info); if (info.st_mode & S_IRUSR) { printf("Owner has read permission\n"); }

37. Example: Checking Multiple Permissions

if (info.st_mode & S_IWUSR) { printf("Owner can write\n"); } if (info.st_mode & S_IXUSR) { printf("Owner can execute\n"); }

38. Permission Interpretation

st_mode ↓ Permission Bits ↓ Owner ↓ Group ↓ Others ↓ Read / Write / Execute

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

  1. Which member of struct stat stores the permission bits?
  2. How many permission categories exist in UNIX?
  3. What are the three basic file permissions?
  4. What does S_IRUSR represent?
  5. How can a program determine whether the owner has write permission?
  6. What is the purpose of S_IXGRP?
  7. 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.

#include <sys/stat.h> int chmod( const char *pathname, mode_t mode );

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()

#include <sys/stat.h> int main() { if (chmod("sample.txt", 0644) == -1) { perror("chmod"); return 1; } return 0; }

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.

#include <sys/stat.h> int fchmod( int fd, mode_t mode );

45. Example: Using fchmod()

#include <fcntl.h> #include <sys/stat.h> int fd; fd = open("sample.txt", O_RDWR); if (fd != -1) { fchmod(fd, 0600); }

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

Application ↓ chmod() or fchmod() ↓ Kernel ↓ Validate Permissions ↓ Update st_mode ↓ Write Updated Metadata ↓ Return Status

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

  1. What is the purpose of chmod()?
  2. What is the difference between chmod() and fchmod()?
  3. Who is allowed to change file permissions?
  4. What does the permission value 0644 represent?
  5. When should fchmod() be preferred over chmod()?
  6. What does the kernel update when chmod() succeeds?
  7. 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.

#include <sys/stat.h> mode_t umask( mode_t mask );

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.

Requested Mode ↓ umask() ↓ Kernel Clears Masked Bits ↓ Final File Permissions

53. Example: Using umask()

#include <sys/stat.h> #include <fcntl.h> int main() { umask(022); creat("sample.txt", 0666); return 0; }

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.

#include <unistd.h> int chown( const char *pathname, uid_t owner, gid_t group );

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.

#include <unistd.h> int fchown( int fd, uid_t owner, gid_t group );

57. Example: Using chown()

#include <unistd.h> int main() { if (chown("sample.txt", 1000, 1000) == -1) { perror("chown"); return 1; } return 0; }

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

Application ↓ chown() or fchown() ↓ Kernel ↓ Validate Privileges ↓ Update Owner and Group ↓ Modify File Metadata ↓ Return Status

60. Interview Questions

  1. What is the purpose of umask()?
  2. How does umask() affect newly created files?
  3. Why does umask() not modify existing file permissions?
  4. What is the relationship between open(), creat(), and umask()?
  5. What is the purpose of chown()?
  6. What is the difference between chown() and fchown()?
  7. Which members of struct stat store 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.

#include <unistd.h> int access( const char *pathname, int mode );

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()

#include <unistd.h> #include <stdio.h> int main() { if (access("sample.txt", R_OK) == 0) { printf("Readable\n"); } else { printf("Read permission denied\n"); } return 0; }

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.

#include <fcntl.h> #include <unistd.h> int faccessat( int dirfd, const char *pathname, int mode, int flags );

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

Read File ↓ st_atime Updated ────────────── Modify File Data ↓ st_mtime Updated ────────────── Change Metadata ↓ st_ctime Updated

69. Example: Displaying File Attributes

#include <stdio.h> #include <sys/stat.h> #include <time.h> int main() { struct stat info; if (stat("sample.txt", &info) == 0) { printf("Size: %ld\n", (long)info.st_size); printf("Modified: %s", ctime(&info.st_mtime)); } return 0; }

70. Interview Questions

  1. What is the purpose of access()?
  2. Which IDs are used by access() for permission checking?
  3. How does access() differ from open()?
  4. What is the difference between the real user ID and the effective user ID?
  5. What do F_OK, R_OK, W_OK, and X_OK represent?
  6. What does st_atime record?
  7. What is the difference between st_mtime and st_ctime?
  8. Does st_ctime represent 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

Create File ↓ umask() ↓ File Created ↓ stat() ↓ Read Metadata ↓ Modify Permissions ↓ chmod() ↓ Modify Ownership ↓ chown() ↓ Verify Metadata ↓ stat()

77. Advanced Interview Questions

  1. Explain the relationship between directories, file names, inodes, and data blocks.
  2. Differentiate stat(), fstat(), and lstat().
  3. Why is st_mode divided into file type bits and permission bits?
  4. Explain how umask() affects file creation.
  5. Why should S_ISREG() be used instead of checking bit patterns directly?
  6. Compare chmod() with fchmod().
  7. Compare chown() with fchown().
  8. Why does access() use the real user ID?
  9. Explain the purpose of st_atime, st_mtime, and st_ctime.
  10. Describe a complete workflow for securely creating and configuring a new file.
Knowledge Check

Concept Mastery Assessment — Module 23

Verify your conceptual understanding with 12 targeted technical assessment questions. Instant feedback and explanations are provided for every choice.

Question 1 of 12
What is the primary architectural purpose of File and Directory Attributes & Permissions in operating systems?
Explanation
File and Directory Attributes & Permissions is designed to manage stat/fstat structures, file types, st_mode bitmasks, uid/gid ownership, umask calculation, and setuid/setgid execution bits. within the operating system architecture.
Question 2 of 12
Which system interface or data structure is centrally associated with File and Directory Attributes & Permissions?
Explanation
Under POSIX and Linux, File and Directory Attributes & Permissions operates through standardized system calls and kernel control structures.
Question 3 of 12
What safety or concurrency constraint must developers consider when implementing File and Directory Attributes & Permissions?
Explanation
Proper synchronization, avoidance of race conditions, and handling reentrant execution are critical when working with File and Directory Attributes & Permissions.
Question 4 of 12
When a system call related to File and Directory Attributes & Permissions fails in C, how does the POSIX runtime conventionally report the failure?
Explanation
Standard POSIX system calls return -1 or NULL on error, assigning an error integer (e.g. EINVAL, EPERM, EAGAIN) to the thread-local errno variable.
Question 5 of 12
What is the primary performance tradeoff associated with File and Directory Attributes & Permissions?
Explanation
Operations involving File and Directory Attributes & Permissions balance performance against kernel transition, memory bandwidth, and cache locality tradeoffs.
Question 6 of 12
What security principle governs access to resources in File and Directory Attributes & Permissions?
Explanation
The kernel validates credentials, effective permissions, and Linux capabilities before granting access to protected operations.
Question 7 of 12
How does execution of File and Directory Attributes & Permissions transition between User Space and Kernel Space?
Explanation
User space transitions to kernel mode securely via software traps or SYSCALL instructions that switch processor rings to Ring 0.
Question 8 of 12
What happens to resources allocated by File and Directory Attributes & Permissions when the owning process terminates?
Explanation
Process resources (open fds, memory maps) are automatically reclaimed by the kernel on termination, while kernel-persistent objects survive.
Question 9 of 12
In production Linux server environments, how is File and Directory Attributes & Permissions optimized for high throughput?
Explanation
Linux optimizes throughput via zero-copy data paths, asynchronous kernel events, and scalable concurrency primitives.
Question 10 of 12
What standard governs the portability of File and Directory Attributes & Permissions across Unix, Linux, and macOS platforms?
Explanation
IEEE POSIX standards define consistent APIs across Unix-like platforms ensuring portable source code execution.
Question 11 of 12
Which command-line diagnostic tool is most effective for inspecting and troubleshooting File and Directory Attributes & Permissions at runtime?
Explanation
Utilities like strace, lsof, and the /proc filesystem provide direct visibility into kernel interactions and resource status.
Question 12 of 12
What is a critical production best practice when developing systems software involving File and Directory Attributes & Permissions?
Explanation
Defensive programming requires explicit error checking on all system operations, proper resource cleanup, and avoiding memory corruption.
0 / 12 (0%)
Great job! Review the concepts above and proceed when ready.
ADVERTISEMENT
Responsive Ad Unit • Technical Courses & Certifications