Reading and Deleting Directories
This lesson goes into details of how to read and delete directories.
We'll cover the following
Reading directories
Now that we’ve created a directory, we might wish to read one too. Indeed, that is exactly what the program ls
does. Let’s write our own little tool like ls and see how it is done.
Instead of just opening a directory as if it were a file, we instead use a new set of calls. Below is an example program that prints the contents of a directory. The program uses three calls, opendir()
, readdir()
, and closedir()
, to get the job done, and you can see how simple the interface is. We just use a simple loop to read one directory entry at a time, and print out the name and inode number of each file in the directory.
int main(int argc, char *argv[]) {DIR *dp = opendir(".");assert(dp != NULL);struct dirent *d;while ((d = readdir(dp)) != NULL) {printf("%lu %s\n", (unsigned long) d->d_ino,d->d_name);}closedir(dp);return 0;}
The declaration below shows the information available within each directory entry in the struct dirent
data structure:
struct dirent {char d_name[256]; // filenameino_t d_ino; // inode numberoff_t d_off; // offset to the next direntunsigned short d_reclen; // length of this recordunsigned char d_type; // type of file};
Because directories are light on information (basically, just mapping the name to the inode number, along with a few other details), a program may want to call stat()
on each file to get more information on each, such as its length or other detailed information. Indeed, this is exactly what ls
does when you pass it the -l
flag; try strace
on ls
with and without that flag to see for yourself.
Deleting directories
Finally, you can delete a directory with a call to rmdir()
(which is used by the program of the same name, rmdir
). Unlike file deletion, however, removing directories is more dangerous, as you could potentially delete a large amount of data with a single command. Thus, rmdir()
has the requirement that the directory be empty (i.e., only has .
and ..
entries) before it is deleted. If you try to delete a non-empty directory, the call to rmdir()
simply will fail. You can reuse the above terminal to try rmdir
.
Get hands-on with 1400+ tech skills courses.