Look, we saw the first program in this book.
1#include"apue.h"2#include <dirent.h>3 4 int5MainintargcChar*argv[])6 {7DIR *DP;8 structDirent *Dirp;9 Ten if(ARGC! =2) OneErr_quit ("Usage:ls Directory_name"); A - if(DP = Opendir (argv[1])) ==NULL) -Err_sys ("can ' t open%s", argv[1]); the while((DIRP = Readdir (DP))! =NULL) -printf"%s\n", dirp->d_name); - - Closedir (DP); +Exit0); -}
This program is almost the same as the LS command, which has no option in Linux, and displays the names of all the files in a directory (excluding hidden files).
He first used a header file written by the master himself. This header contains a number of constants (such as Maxline) and prototypes of the Master's self-editing functions. It also includes the usual header files such as <stdio.h>, <stdilb.h>, <unistd.h> and <string.h> to reduce the length of the code in the book.
Next he used the Dirent.h's header file. This header file is the header file for UNIX class directory operations defined by the POSIX.1 standard, and contains many of the functions prototypes for UNIX system services , such as opendir functions, readdir functions.
The next step is the main function. See the main function main inside the parameters, a lot of people are confused, the parameters in this is what things! ARGC and argv are a very strange thing for children who are accustomed to Windows. ARGC stores the number of command-line arguments, and the command-line arguments are stored in the argv array. Give me a chestnut and look at the code below.
1#include <stdio.h>2 intMainintargcChar*argv[])3 {4 intn =argc, I;5printf"%d\n", n);6 for(i =0; I < n; i++)7 {8printf"%s\n", Argv[i]);9 }Ten return 0; One}
After I compile it, enter the following command in the terminal
./a.out I Love Loli
It will give me the following display:
4./a.outiloveloli
ARGC default value is 1, that is, I execute the path of the program, the parameters are separated by a space. This example should allow you to understand this argc and argv.
In the middle of the code there are two error handling, is the master self-compiled, in the master's self-made header file can find its prototype and interpretation.
As for the middle Opendir and Readdir, it is the function that opens the directory and reads the directory, these are all in the Dirent.h header file, which I will explain in detail in later chapters.
The code in this book without any foundation of the case, is very obscure, but its structure and ideas are very clear, so I am here to give you a science, convenient for everyone to learn later.
"UNIX Environment Advanced Programming" learning Experience II