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

2   * перечисляет файлы или каталоги

3   */

4

5  #include

6  #include

7  #include

8  #include

9

10 #define NFILES 1024

11 FILE *pwdf, *dirf;

12 char stdbuf[BUFSIZ];

13

14 struct lbuf { /* Собирает необходимые сведения */

15  union {

16   char lname[15];

17   char *namep;

18  } ln;

19  char ltype;

20  short lnum;

21  short lflags;

22  short lnl;

23  short luid;

24  short lgid;

25  long lsize;

26  long lmtime;

27 };

28

29 int aflg, dflg, lflg, sflg, tflg, uflg, lflg, fflg, gflg, cflg;

30 int rflg = 1;

31 long year; /* Глобальные переменные: инициализируются 0 */

32 int flags;

33 int lastuid = -1;

34 char tbuf[16];

35 long tblocks;

36 int statreq;

37 struct lbuf *flist[NFILES];

38 struct lbuf **lastp = flist;

39 struct lbuf **firstp = flist;

40 char *dotp = ".";

41

42 char *makename(); /* char *makename(char *dir, char *file); */

43 struct lbuf *gstat(); /* struct lbuf *gstat(char *file, int argfl); */

44 char *ctime(); /* char *ctime(time_t *t); */

45 long nblock(); /* long nblock(long size); */

46

47 #define ISARG 0100000

Программа начинается с включения файлов (строки 5–8) и объявлений переменных. struct lbuf (строки 14–27) инкапсулирует части struct stat, которые интересны ls. Позже мы увидим, как эта структура заполняется.

Переменные aflg, dflg и т.д. (строки 29 и 30) все указывают на наличие соответствующей опции. Такой стиль именования переменных типичен для кода V7. Переменные flist, lastp и firstp (строки 37–39) представляют файлы, о которых ls выводит сведения. Обратите внимание, что flist является массивом фиксированного размера, которая позволяет обрабатывать не более 1024 файлов. Вскоре мы увидим, как используются все эти переменные.

После объявлений переменных идут объявления функций (строки 42–45), а затем определение ISARG, которая различает файл, указанный в командной строке, от файла, найденного при чтении каталога.

49 main(argc, argv) /* int main(int argc, char **argv) */

50 char *argv[];

51 {

52  int i;

53  register struct lbuf *ep, **ep1; /* Объявления переменных и функций */

54  register struct lbuf **slastp;

55  struct lbuf **epp;

56  struct lbuf lb;

57  char *t;

58  int compar();

59

60  setbuf(stdout, stdbuf);

61  time(&lb.lmtime); /* Получить текущее время */

62  year = lb.lmtime - 6L*30L*24L*60L*60L; /* 6 месяцев назад */

Функция main() начинается с объявления переменных и функций (строки 52–58), устанавливая буфер для стандартного вывода, получая время дня (строки 60–61) и вычисляя значение секунд с начала Эпохи для примерно шести месяцев (строка 62). Обратите внимание, что у всех констант есть суффикс L, указывающий на использование арифметики long.

63  if (--argc > 0 && *argv[1] == '-') {

64   argv++;

65   while (*++*argv) switch(**argv) { /* Разбор опций */

66

67   case 'a': /* Все элементы каталога */

68    aflg++;

69    continue;

70

71   case 's': /* Размер в блоках */

72    sflg++;

73    statreq++;

74    continue;

75

76   case 'd': /* Сведения о каталоге, не содержание */

77    dflg++;

78    continue;

79

80   case 'g': /* Имя группы вместо имени владельца */

81    gflg++;

82    continue;

83

84   case 'l': /* Расширенный листинг */

85    lflg++;

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

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

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

Стивен Прата

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