Unit 2 Directories
Unit 2 Directories
chdir
In Linux, the system calls mkdir, rmdir, and chdir are used to perform operations on
directories at a low level, typically within a C program or other system-level
programming environments. Here’s a brief overview of each:
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <unistd.h>
Summary:
int main() {
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
printf("Current working directory: %s\n", cwd);
} else {
perror("getcwd() error");
}
return 0;
}
2. Listing Directory Contents Using System Calls
To list the contents of a directory, you typically use the following system calls:
opendir: Opens a directory for reading.
readdir: Reads the next directory entry.
closedir: Closes the directory stream.
opendir: Opening a Directory
Prototype: DIR *opendir(const char *name);
Parameters:
o name: The path of the directory you want to open.
Return Value:
o Returns a pointer to a DIR structure on success.
o Returns NULL on failure, and errno is set to indicate the error.
readdir: Reading Directory Entries
Prototype: struct dirent *readdir(DIR *dirp);
Parameters:
o dirp: A pointer to the DIR structure returned by opendir.
Return Value:
o Returns a pointer to a struct dirent on success.
o Returns NULL when the end of the directory is reached or on error.
struct dirent: This structure typically contains fields like:
o d_name: Name of the directory entry (file or subdirectory).
o d_ino: Inode number.
o (Note: struct dirent may have additional fields depending on the
system.)
closedir: Closing a Directory
Prototype: int closedir(DIR *dirp);
Parameters:
o dirp: A pointer to the DIR structure returned by opendir.
Return Value:
o Returns 0 on success.
o Returns -1 on failure, and errno is set to indicate the error.
Example: Listing Directory Contents
#include <stdio.h>
#include <dirent.h>
int main() {
DIR *d;
struct dirent *dir;
d = opendir("/path/to/directory");
if (d) {
while ((dir = readdir(d)) != NULL) {
printf("%s\n", dir->d_name);
}
closedir(d);
} else {
perror("opendir() error");
}
return 0;
}
Summary:
getcwd: Retrieves the current working directory.
opendir: Opens a directory for reading.
readdir: Reads the contents of the directory.
closedir: Closes the directory stream.
These system calls are essential for navigating and managing directories
programmatically in Linux at a low level.
Scanning Directories – opendir, readdir, closedir, rewinddir
functions
int main() {
DIR *dir;
struct dirent *entry;
return 0;
}
Summary:
opendir: Opens a directory stream.
readdir: Reads the next entry from the directory stream.
rewinddir: Resets the directory stream to the beginning.
closedir: Closes the directory stream.
These functions are essential for directory manipulation in C programs on Linux,
providing the means to efficiently scan and manage directory contents.