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

Когда цикл завершается, либо бит разрешения был найден, в этом случае pairp указывает на второй элемент пары, являющийся нужным для вывода символом, либо он не был найден, в этом случае pairp указывает на символ по умолчанию. В любом случае, строка 274 выводит символ, на который указывает pairp.

Последним стоящим внимания моментом является то, что на С символьные константы (такие как 'x') имеют тип int, а не char[75]. Поэтому проблем с помещением этих констант в массив целых нет; все работает правильно.

277 char* /* char *makename(char *dir, char *file) */

278 makename(dir, file)

279 char *dir, *file;

280 {

281  static char dfile[100];

282  register char *dp, *fp;

283  register int i;

284

285  dp = dfile;

286  fp = dir;

287  while (*fp)

288   *dp++ = *fp++;

289  *dp++ = '/';

290  fp = file;

291  for (i=0; i

292   *dp++ = * fp++;

293  *dp = 0;

294  return(dfile);

295 }

Строки 277–295 определяют функцию makename(). Ее работа заключается в соединении имени каталога с именем файла, разделенным символом косой черты, с образованием строки. Она осуществляет это в static буфере dfile. Обратите внимание, что dfile всего лишь 100 символов длиной и что проверка ошибок не выполняется.

Сам код прост, он копирует по одному символу за раз. makename() используется функцией readdir().

297 readdir(dir) /* void readdir(char *dir) */

298 char *dir;

299 {

300  static struct direct dentry;

301  register int j;

302  register struct lbuf *ep;

303

304  if ((dirf = fopen(dir, "r")) == NULL) {

305   printf("%s unreadable\n", dir);

306   return;

307  }

308  tblocks = 0;

309  for(;;) {

310   if (fread((char*)&dentry, sizeof(dentry), 1, dirf) != 1)

311    break;

312   if (dentry.d_ino==0

313    || aflg==0 && dentry.d_name[0]=='.' && (dentry.d_name[1]=='\0'

314    || dentry.d_name[1]=='.' && dentry, d_name[2]=='\0'))

315    continue;

316   ep = gstat(makename(dir, dentry.d_name), 0);

317   if (ep==NULL)

318    continue;

319   if (ep->lnum != -1)

320    ep->lnum = dentry.d_ino;

321   for (j =0; j

322    ep->ln.lname[j] = dentry.d_name[j];

323  }

324  fclose(dirf);

325 }

Строки 297–325 определяют функцию readdir(), чья работа заключается в чтении содержимого каталогов, указанных в командной строке.

Строки 304–307 открывают каталог для чтения, завершая функцию, если fopen() возвращает ошибку. Строка 308 инициализирует глобальную переменную tblocks нулем. Ранее (строки 153–154) это использовалось для вывода общего числа блоков, использованных файлами в каталоге.

Строки 309–323 являются циклом, который читает элементы каталога и добавляет их к массиву flist. Строки 310–311 читают один элемент, выходя из цикла в конце файла.

Строки 312–315 пропускают неинтересные элементы. Если номер индекса равен нулю, этот слот не используется. В противном случае, если не был указан -а и имя файла является '.' или '..', оно пропускается.

Строки 316–318 вызывают gstat() с полным именем файла и вторым аргументом, равным false, указывающим, что он не из командной строки. gstat() обновляет глобальный указатель lastp и массив flist. Возвращаемое значение NULL обозначает какую-нибудь разновидность ошибки.

Строки 319–322 сохраняют номер индекса и имя в struct lbuf. Если ep->lnum возвращается из gstat() установленным в -1, это означает, что операция stat() с файлом завершилась неудачей. Наконец, строка 324 закрывает каталог.

Следующая функция, gstat() (строки 327–398), является центральной функцией для получения и сохранения сведений о файле.

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

328 gstat(file, argfl)

329 char *file;

330 {

331  extern char *malloc();

332  struct stat statb;

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

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

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

Стивен Прата

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