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

Для максимальной переносимости мы использовали difftime(), которая возвращает разницу в секундах между двумя значениями time_t. Для данного конкретного случая приведение, такое, как

return (int)difftime(e1->start_date, e2->start_date);

должно сработать, поскольку значения time_t находятся в приемлемом диапазоне. Тем не менее, мы вместо этого использовали полный трехсторонний оператор if, просто из предосторожности.

Вот пример файла данных со списком пяти президентов США:

$ cat presdata.txt

/* Фамилия, имя, номер президента, инаугурация */

Bush George 43 980013600

Clinton William 42 727552800

Bush George 41 601322400

Reagan Ronald 40 348861600

Carter James 39 222631200

В ch06-sortemp.c приведена простая программа, которая считывает этот файл в массив struct employee, а затем сортирует его, используя две только что представленные функции сравнения.

1   /* ch06-sortemp.c --- Демонстрирует qsort() с двумя функциями сравнения. */

2

3   #include

4   #include

5   #include

6

7   struct employee {

8    char lastname[30];

9    char firstname[30];

10   long emp_id;

11   time_t start_date;

12  };

13

14  /* emp_name_id_compare --- сравнение по имени, затем no ID */

15

16  int emp_name_id_compare(const void *e1p, const void *e2p)

17  {

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

39  }

40

41  /* emp_seniority_compare --- сравнение по старшинству */

42

43  int emp_seniority_compare(const void *e1p, const void *e2p)

44  {

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

58  }

59

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

61

62  int main(void)

63  {

64   #define NPRES 10

65   struct employee presidents[NPRES];

66   int i, npres;

67   char buf[BUFSIZ];

68

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

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

71    npres++) {

72    sscanf(buf, "%s %s %ld %ld\n",

73     presidents[npres].lastname,

74     presidents[npres].firstname,

75     &presidents[npres].emp_id,

76     &presidents[npres].start_date);

77   }

78

79   /* npres теперь содержит число прочитанных строк. */

80

81   /* Сначала сортировка по имени */

82   qsort(presidents, npres, sizeof(struct employee), emp_name_id_compare);

83

84   /* Вывести результат */

85   printf("Sorted by name:\n");

86   for (i = 0; i < npres; i++)

87    printf("\t%s %s\t%d\t%s",

88     presidents[i].lastname,

89     presidents[i].firstname,

90     presidents[i].emp_id,

91     ctime(&presidents[i].start_date));

92

93   /* Теперь сортировка по старшинству */

94   qsort(presidents, npres, sizeof(struct employee), emp_seniority_compare);

95

96   /* И снова вывести */

97   printf("Sorted by seniority:\n");

98   for (i = 0; i < npres; i++)

99    printf("\t%s %s\t%d\t%s",

100    presidents[i].lastname,

101    presidents!i].firstname,

102    presidents[i].emp_id,

103    ctime(&presidents[i].start_date));

104 }

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

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

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

Стивен Прата

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