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

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

36  #define PROGRAM_NAME "link"

37

38  #define AUTHORS "Michael Stone"

39

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

41  char *program_name;

42

43  void

44  usage(int status)

45  {

     /*  ... для краткости опущено... */

62  }

63

64  int

65  main(int argc, char **argv)

66  {

67   program_name = argv[0];

68   setlocale(LC_ALL, "");

69   bindtextdomain(PACKAGE, LOCALEDIR);

70   textdomain(PACKAGE);

71

72   atexit(close_stdout);

73

74   parse_long_options(argc, argv, PROGRAM_NAME, GNU_PACKAGE,

75    VERSION, AUTHORS, usage);

76

77   /* Вышеприведенное обрабатывает --help и --version.

78      Поскольку других вызовов getopt нет, обработать здесь '--'. */

79   if (1 < argc && STREQ(argv[1], "--"))

80   {

81    --argc;

82    ++argv;

83   }

84

85   if (argc < 3)

86   {

87    error(0, 0, _("too few arguments"));

88    usage(EXIT_FAILURE);

89   }

90

91   if (3 < argc)

92   {

93    error(0, 0, _("too many arguments"));

94    usage(EXIT_FAILURE);

95   }

96

97   if (link(argv[1], argv[2]) != 0)

98    error(EXIT_FAILURE, errno, _("cannot create link %s to %s"),

99     quote_n(0, argv[2]), quote_n(1, argv[1]));

100

101  exit(EXIT_SUCCESS);

102 }

Строки 67–75 являются типичным шаблоном Coreutils, устанавливающими интернациональные настройки, выход по завершении и анализ аргументов. Строки 79–95 гарантируют, что link вызывается лишь с двумя аргументами. Сам системный вызов link() осуществляется в строке 97 (Функция quote_n() обеспечивает отображение аргументов в стиле, подходящем для текущей локали; подробности сейчас несущественны.)

<p>5.1.3.2. Точка и точка-точка</p>

Завершая обсуждение ссылок, давайте взглянем на то, как обрабатываются специальные имена '.' и '..'. На самом деле они просто являются прямыми ссылками. В первом случае '.' является прямой ссылкой на каталог, содержащий ее, а '..' — прямой ссылкой на родительский каталог. Операционная система создает для вас эти ссылки; как упоминалось ранее, код уровня пользователя не может создать прямую ссылку на каталог. Этот пример иллюстрирует ссылки:

$ pwd /* Отобразить текущий каталог */

/tmp

$ ls -ldi /tmp /* Показать номер его индекса */

225345 drwxrwxrwt 14 root root 4096 May 4 16:15 /tmp

$ mkdir x /* Создать новый каталог */

$ ls -ldi x /* И показать номер его индекса */

52794 drwxr-xr-x 2 arnold devel 4096 May 4 16:27 x

$ ls -ldi x/. x/.. /* Показать номера индексов . И .. */

52794 drwxr-xr-x 2 arnold devel 4096 May 4 16:27 x/.

225345 drwxrwxrwt 15 root root 4096 May 4 16:27 x/..

Родительский каталог корневого каталога (/..) является особым случаем; мы отложим его обсуждение до главы 8 «Файловые системы и обход каталогов».

<p>5.1.4. Переименование файлов</p>

При данном способе отображения элементами каталога имен на номера индексов, переименование файла концептуально очень просто:

1. Если новое имя файла обозначает существующий файл, сначала удалить этот файл.

2. Создать новую ссылку на файл через новое имя.

3. Удалить старое имя (ссылку) для файла. (Удаление имен обсуждается в следующем разделе.)

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

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

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

Стивен Прата

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