Implementation of ls commands in Linux
The ls command is one of the most common commands in Linux. the dir commands in ls and dos are used to list files in the directory. Let's take a look at the ls implementation method.
Implementation of ls commands in Linux
Ls command: 15 interview-level questions for Linux-Episode 1
Ls command: Ten interview-level questions-Episode 2
# Include <dirent. h>
It is the header file for POSIX.1 standard-defined unix class directory operations, including the function prototype of many UNIX system services, such as opendir function and readdir function.
Opendir function:
DIR * opendir (const char * pathname); Return Value: If successful, the pointer is returned. If an error occurs, NULL is returned.
Struct dirent * readdir (DIR * dp); Return Value: If successful, the pointer is returned. If the directory ends or fails, NULL is returned.
Brief Implementation of ls:
Write makefile
Run the test:
-------------------------------------- Split line --------------------------------------
See the following procedure:
# Include <sys/types. h>
# Include <dirent. h>
# Include <stdio. h>
Int main (int argc, int * argv [])
{
DIR * dir;
Struct dirent * dirp;
If (argc! = 2)
{
Printf ("usage: % s directory_name \ n", argv [0]);
Return-1;
}
If (! (Dir = opendir (argv [1])
{
Printf ("can not open % s \ n", argv [1]);
Return-1;
}
While (dirp = readdir (dir ))! = NULL)
{
Printf ("% s \ n", dirp-> d_name );
}
Closedir (dir );
Return 0;
}
Describe several important struct and functions.
Opendir
Opendir () is used to open the directory specified by the parameter name and return the DIR * Format
Directory stream, similar to open (), which is used for reading and searching directories,
If the operation succeeds, the directory stream of the DIR * type is returned. If the operation fails, the return value is NULL.
Readdir () returns the next directory entry point of the dir directory stream parameter. Structure dirent Definition
As follows:
Struct dirent
{
Long d_ino;/* inode number */index node number
Off_t d_off;/* offset to this dirent */offset in the directory file
Unsigned short d_reclen;/* length of this d_name */File Name length
Unsigned char d_type;/* the type of d_name */file type
Char d_name [NAME_MAX + 1];/* file name (null-terminated) */file name, which can contain a maximum of 255 characters
}
If the operation succeeds, the next directory entry point is returned. If an error occurs or the end of the directory file is read, NULL is returned.
This article permanently updates the link address: