Читаем Linux программирование в примерах полностью

--help                   /* показать этот экран справки и выйти */

--version                /* вывести информацию о версии и выйти */

/* Простое - предполагает -1. Если не указана COMMAND, отображает

   имеющееся окружение.

Об ошибках сообщайте в . */

Вот несколько примеров вызовов команды:

$ env - myprog arg1 /* Очистить окружение, запустить программу с args */

$ env - РАТН=/bin:/usr/bin myprog arg1 /* Очистить окружение, добавить PATH, запустить программу */

$ env -u IFS PATH=/bin:/usr/bin myprog arg1 /* Сбросить IFS, добавить PATH, запустить программу */

Код начинается со стандартной формулировки авторских прав GNU и разъясняющего комментария. Мы для краткости их опустили. (Формулировка авторского права обсуждается в Приложении С «Общедоступная лицензия GNU». Показанного ранее вывода --help достаточно для понимания того, как работает программа.) За объявленным авторским правом и комментарием следуют подключаемые заголовочные файлы и объявления. Вызов макроса 'N_("string")' (строка 93) предназначен для использования при локализации программного обеспечения, тема, освещенная в главе 13 «Интернационализация и локализация». Пока вы можете рассматривать его, как содержащий строковую константу.

80  #include

81  #include

82  #include

83  #include

84  #include

85

86  #include "system.h"

87  #include "error.h"

88  #include "closeout.h"

89

90  /* Официальное имя этой программы (напр., нет префикса 'g'). */

91  #define PROGRAM_NAME "env"

92

93  #define AUTHORS N_ ("Richard Mlynarik and David MacKenzie")

94

95  int putenv();

96

97  extern char **environ;

98

99  /* Имя, посредством которого эта программа была запущена. */

100 char *program_name;

101

102 static struct option const longopts[] =

103  {

104  {"ignore-environment", no_argument, NULL, 'i'},

105  {"unset", required_argument, NULL, 'u'},

106  {GETOPT_HELP_OPTION_DECL},

107  {GETOPT_VERSION_OPTION_DECL},

108  {NULL, 0, NULL, 0}

109 };

GNU Coreutils содержит большое число программ, многие из которых выполняют одни и те же общие задачи (например, анализ аргументов). Для облегчения сопровождения многие типичные идиомы были определены в виде макросов. Двумя таким макросами являются GETOPT_HELP_OPTION_DECL и GETOPT_VERSION_OPTION (строки 106 и 107). Вскоре мы рассмотрим их определения. Первая функция, usage(), выводит информацию об использовании и завершает программу. Макрос _("string") (строка 115, используется также по всей программе) также предназначен для локализации, пока также считайте его содержащим строковую константу.

111 void

112 usage(int status)

113 {

114  if (status '= 0)

115   fprintf(stderr, _("Try '%s --help' for more information.\n"),

116    program_name);

117  else

118  {

119   printf (_("\

120    Usage: %s [OPTION]... [-] [NAME=VALUE]... [COMMAND [ARG]...]\n"),

121    program_name);

122   fputs (_("\

123    Set each NAME to VALUE in the environment and run COMMAND. \n\

124    \n\

125    -i, --ignore-environment start with an empty environment\n\

126    -u, --unset=NAME remove variable from the environment\n\

127    "), stdout);

128   fputs(HELP_OPTION_DESCRIPTION, stdout);

129   fputs(VERSION_OPTION_DESCRIPTION, stdout);

130   fputs(_("\

131    \n\

Перейти на страницу:

Похожие книги

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных