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

132    A mere - implies -i. If no COMMAND, print the resulting\

133    environment.\n"), stdout);

134   printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);

135  }

136  exit(status);

137 }

Первая часть main() объявляет переменные и настраивает локализацию. Функции setlocale(), bindtextdomain() и textdomain() (строки 147–149) обсуждаются в главе 13 «Интернационализация и локализация». Отметим, что эта программа использует аргумент main() envp (строка 140). Это единственная программа Coreutils, которая так делает. Наконец, вызов atexit() в строке 151 (см. раздел 9.1.5.3. «Функции завершения») регистрирует библиотечную функцию Coreutils, которая очищает все выходные буферы и закрывает stdout, выдавая сообщение при ошибке. Следующая часть программы обрабатывает аргументы командной строки, используя getopt_long().

139 int

140 main(register int argc, register char **argv, char **envp)

141 {

142  char *dummy_environ[1];

143  int optc;

144  int ignore_environment = 0;

145

146  program_name = argv[0];

147  setlocale(LC_ALL, "");

148  bindtextdomain(PACKAGE, LOCALEDIR);

149  textdomain(PACKAGE);

150

151  atexit(close_stdout);

152

153  while ((optc = getopt_long(argc, argv, "+iu:", longopts, NULL)) != -1)

154  {

155   switch (optc)

156   {

157   case 0:

158    break;

159   case 'i':

160    ignore_environment = 1;

161    break;

162   case 'u':

163    break;

164   case_GETOPT_HELP_CHAR;

165   case_GETOPT_VERSION_CHAR(PROGRAM_NAME, AUTHORS);

166   default:

167    usage(2);

168   }

169  }

170

171  if (optind != argc && !strcmp(argv[optind], "-"))

172   ignore_environment = 1;

Вот отрывок из файла src/sys2.h в дистрибутиве Coreutils с упомянутыми ранее определениями и макросом 'case_GETOPT_xxx', использованным выше (строки 164–165):

/* Вынесение за скобки общей части кода, обрабатывающего --help и

   --version. */

/* Эти значения перечисления никак не могут конфликтовать со значениями опций,

   обычно используемыми командами, включая CHAR_MAX + 1 и т.д. Избегайте

   CHAR_MIN - 1, т.к. оно может равняться -1, значение завершения опций getopt.

*/

enum {

 GETOPT_HELP_CHAR = (CHAR_MIN — 2),

 GETOPT_VERSION_CHAR = (CHAR_MIN - 3)

};

#define GETOPT_HELP_OPTION_DECL \

 "help", no_argument, 0, GETOPT_HELP_CHAR

#define GETOPT_VERSION_OPTION_DECL \

 "version", no_argument, 0, GETOPT_VERSION_CHAR

#define case_GETOPT_HELP_CHAR \

 case GETOPT_HELP_CHAR: \

  usage(EXIT_SUCCESS); \

  break;

#define case_GETOPT_VERSION_CHAR(Program_name, Authors) \

 case GETOPT_VERSION_CHAR: \

  version_etc(stdout, Program_name, PACKAGE, VERSION, Authors); \

  exit(EXIT_SUCCESS); \

  break;

Результатом этого кода является печать сообщения об использовании утилиты для --help и печать информации о версии для --version. Обе опции завершаются успешно («Успешный» и «неудачный» статусы завершения описаны в разделе 9.1.5.1 «Определение статуса завершения процесса».) Поскольку в Coreutils входят десятки утилит, имеет смысл вынести за скобки и стандартизовать как можно больше повторяющегося кода.

Возвращаясь к env.с:

174 environ = dummy_environ;

175 environ[0] = NULL;

176

177 if (!ignore_environment)

178  for (; *envp; envp++)

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

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

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

Стивен Прата

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