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

26   return 0;

27  else

28   return 1;

29 }

30

31 /* print_employee --- напечатать структуру сотрудника */

32

33 void print_employee(const struct employee *emp)

34 {

35  printf("%s %s\t%d\t%s", emp->lastname, emp->firstname,

36  emp->emp_id, ctime(&emp->start_date));

37 }

Строки 7–12 определяют struct employee; она та же, что и раньше. Строки 16–29 служат в качестве функции сравнения как для qsort(), так и для bsearch(). Они сравнивают лишь ID сотрудников. Строки 33–37 определяют print_employee(), которая является удобной функцией для печати структуры, поскольку это делается из разных мест.

39 /* main --- демонстрация сортировки */

40

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

42 {

43 #define NPRES 10

44  struct employee presidents[NPRES];

45  int i, npres;

46  char buf[BUFSIZ];

47  struct employee *the_pres;

48  struct employee key;

49  int id;

50  FILE *fp;

51

52  if (argc != 2) {

53   fprintf(stderr, "usage: %s datafile\n", argv[0]);

54   exit(1);

55  }

56

57  if ((fp = fopen(argv[1], "r")) == NULL) {

58   fprintf(stderr, "%s: %s: could not open: %s\n", argv[0],

59    argv[1], strerror(errno));

60   exit(1);

61  }

62

63  /* Очень простой код для чтения данных: */

64  for (npres = 0; npres < NPRES && fgets(buf, BUFSIZ, fp) != NULL;

65   npres++) {

66   sscanf(buf, "%s %s %ld %ld",

67    presidents[npres].lastname,

68    presidents[npres].firstname,

69    &presidents[npres].emp_id,

70    &presidents[npres].start_date);

71  }

72  fclose(fp);

73

74  /* В npres теперь число действительно прочитанных строк. */

75

76  /* Сначала отсортировать по id */

77  qsort(presidents, npres, sizeof(struct employee), emp_id_compare);

78

79  /* Напечатать результат */

80  printf("Sorted by ID:\n");

81  for (i = 0; i < npres; i++) {

82   putchar('\t');

83   print_employee(&presidents[i]);

84  }

85

86  for (;;) {

87   printf("Enter ID number: ");

88   if (fgets(buf, BUFSIZ, stdin) == NULL)

89    break;

90

91   sscanf(buf, "%d\n", &id);

92   key.emp_id = id;

93   the_pres = (struct employee*)bsearch(&key, presidents,

94    npres, sizeof(struct employee), emp_id_compare);

95

96   if (the_pres != NULL) {

97    printf("Found: ");

98    print_employee(the_pres);

99   } else

100   printf("Employee with ID %d not found'\n", id);

101  }

102

103  putchar('\n'); /* Напечатать в конце символ новой строки. */

104

105  exit(0);

106 }

Функция main() начинается с проверки аргументов (строки 52–55). Затем она читает данные из указанного файла (строки 57–72). Стандартный ввод для данных сотрудников использоваться не может, поскольку он зарезервирован для запроса у пользователя ID искомого сотрудника.

Строки 77–84 сортируют, а затем печатают данные. Затем программа входит в цикл, начинающийся со строки 86. Она запрашивает идентификационный номер сотрудника, выходя из цикла по достижению конца файла. Для поиска в массиве мы используем struct employee с именем key. Достаточно лишь установить в его поле emp_id введенный номер ID; другие поля при сравнении не используются (строка 92).

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

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

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

Стивен Прата

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