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

Флаг GLOB_ONLYDIR действует в качестве подсказки реализации, потому что вызывающий интересуется лишь каталогами. Главным его предназначением является использование другими функциями в GLIBC, а вызывающий по-прежнему должен быть готов обрабатывать файлы, не являющиеся каталогами. Вам не следует использовать этот флаг в своих программах.

glob() может быть вызвана более одного раза: при первом вызове флаг GLOB_APPEND не должен быть указан, при всех последующих вызовах он должен быть указан. Вы не можете между вызовами изменять gl_offs, а если вы изменили какие-нибудь значения в gl_pathv или gl_pathc, нужно их восстановить перед последующим вызовом glob().

Возможность многократного вызова glob() позволяет накапливать результаты в одном списке. Это довольно практично, приближается к мощным возможностям раскрывания групповых символов оболочки, но на уровне языка программирования С.

glob() возвращает 0, если не было проблем, или одно из значений из табл. 12.4, если были.

Таблица 12.4. Возвращаемые glob() значения

ФлагЗначение
GLOB_ABORTEDПросмотр остановлен раньше времени, поскольку был установлен GLOB_ERR или функция (*errfunc)() возвратила ненулевой результат
GLOB_NOMATCHНи одно имя файла не соответствовало pattern, а флаг GLOB_NOCHECK не был установлен
GLOB_NOSPACEБыла проблема с выделением динамической памяти

globfree() освобождает всю память, которую динамически выделила glob() Следующая программа, ch12-glob.с, демонстрирует glob():

1  /* ch12-glob.c --- демонстрирует glob(). */

2

3  #include

4  #include

5  #include

6

7  char *myname;

8

9  /* globerr --- выводит сообщение об ошибке для glob() */

10

11 int globerr(const char *path, int eerrno)

12 {

13  fprintf(stderr, "%s: %s: %s\n", myname, path, strerror(eerrno));

14  return 0; /* let glob() keep going */

15 }

16

17 /* main() --- раскрывает символы подстановки в командной строке и выводит результаты */

18

19 int main(int argc, char **argv)

20 {

21  int i;

22  int flags = 0;

23  glob_t results;

24  int ret;

25

26  if (argc == 1) {

27   fprintf(stderr, "usage: %s wildcard ...\n", argv[0]);

28   exit(1);

29  }

30

31  myname = argv[0]; /* для globerr() */

32

33  for (i = 1; i < argc; i++) {

34   flags |= (i > 1 ? GLOB_APPEND : 0);

35   ret = glob(argv[i], flags, globerr, &results);

36   if (ret != 0) {

37    fprintf(stderr, "%s: problem with %s (%s),

38     stopping early\n", myname, argv[i],

39     /* опасно: */ (ret == GLOB_ABORTED ? "filesystem problem" :

40     ret == GLOB_NOMATCH ? "no match of pattern" :

41     ret == GLOB_NOSPACE ? "no dynamic memory" :

42     "unknown problem"));

43    break;

44   }

45  }

46

47  for (i = 0; i < results.gl_pathc; i++)

48   printf("%s\n", results.gl_pathv[i]);

49

50  globfree(&results);

51  return 0;

52 }

Строка 7 определяет myname, которая указывает на имя программы; эта переменная для сообщений об ошибках от globerr(), определенной в строках 11–15.

Строки 33–45 являются основой программы. Они перебирают в цикле шаблоны, приведенные в командной строке, вызывая для каждого glob() для добавления к списку результатов. Большую часть цикла составляет обработка ошибок (строки 36–44). Строки 47–48 выводят результирующий список, а строки 50–51 проводят завершающую очистку и возвращаются.

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

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

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

Стивен Прата

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