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

Функция process() делает всю работу и большую часть кода проверки ошибок. Основой функции являются строки 48 и 49:

while ((ent = readdir(dp)) != NULL)

printf("%8ld %s\n", ent->d_ino, ent->d_name);

Этот цикл читает элементы каталога, по одной за раз, до тех пор, пока readdir() не возвратит NULL. Тело цикла отображает для каждого элемента номер индекса и имя файла. Вот что происходит при запуске программы:

$ ch05-catdir /* По умолчанию текущий каталог */

639063 .

639062 ..

639064 proposal.txt

639012 lightsabers.url

688470 code

638976 progex.texi

639305 texinfo.tex

639007 15-processes.texi

639011 00-preface.texi

639020 18-tty.texi

638980 Makefile

639239 19-i18n.texi

...

Вывод никаким образом не сортируется; он представляет линейное содержимое каталога. (Как сортировать содержимое каталога мы опишем в разделе 6.2 «Функции сортировки и поиска»).

<p>5.3.1.1. Анализ переносимости</p>

Есть несколько соображений по переносимости. Во-первых, не следует предполагать, что двумя первыми элементами, возвращаемыми readdir(), всегда будут '.' и '..'. Многие файловые системы используют организацию каталогов, которые отличаются от первоначального дизайна Unix, и '.' и '..' могут быть в середине каталога или даже вовсе не присутствовать[55].

Во-вторых, стандарт POSIX ничего не говорит о возможных значениях d_info. Он говорит, что возвращенные структуры представляют элементы каталогов для файлов; это предполагает, что readdir() не возвращает пустые элементы, поэтому реализация GNU/Linux readdir() не беспокоится с возвратом элементов, когда 'd_ino == 0'; она переходит к следующему действительному элементу.

Поэтому по крайней мере на системах GNU/Linux и Unix маловероятно, что d_ino когда-нибудь будет равен нулю. Однако, лучше по возможности вообще избегать использования этого поля.

Наконец, некоторые системы используют d_fileno вместо d_ino в struct dirent. Знайте об этом, когда нужно перенести на такие системы код, читающий каталоги.

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

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

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

Стивен Прата

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