在C中按字母顺序对文件中的结构进行排序

Sorting structures from a file alphabetically in C

有必要对字段上的结构进行排序 (char last_name [256];) structures Pers 并在控制台中显示用户。 怎么做? 提前谢谢你。

有这样一个结构(带嵌套):

struct Pers {
    int id;
    char first_name[256];
    char last_name[256];
    struct {
        int age;
        int status;
    } st;
} Pers;


struct Pers sw[2];
char i=0;

从文件中读取并输出如下所示: 一切都按照从文件中读取的顺序显示

 FILE *file;
 file = fopen("1.txt", "r");
 while ( fscanf(file, "%d%s%s%d%d", &sw[i].id,sw[i].first_name,sw[i].last_name,&sw[i].st.age,&sw[i].st.status) != EOF) 
 {

     printf("%d %s %s %d %d\n", sw[i].id, sw[i].first_name, sw[i].last_name, sw[i].st.age, sw[i].st.status);
        i++;
 }

 fclose(file);

要使用 stdlib 中的 qsort 对结构进行排序,您应该实现比较两个元素的函数。并使用 string 中的 strcmp 比较字符串。

详情在 references.

同时使用first_namelast_name进行排序的例子(last_name先进行比较):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int compare (const void * a, const void * b)
{
  const struct Pers * first = (const struct Pers *) a;
  const struct Pers * second = (const struct Pers *) b;
  // compare last names and check result. can be also:
  // if( !strcmp(first->last_name, second->last_name) )
  if( 0 == strcmp(first->last_name, second->last_name) )
      // compare first names if last names are equal
      return strcmp(first->first_name, second->first_name);
  else
      return strcmp(first->last_name, second->last_name);
}

用法:

    printf("Before sorting:\n");
    for(i = 0; i < 2; i++)
    {
        printf("%d %s %s %d %d\n",sw[i].id,sw[i].first_name,sw[i].last_name,sw[i].st.age,sw[i].st.status);
    }
    qsort (sw, 2, sizeof(struct Pers), compare);
    printf("After sorting:\n");
    for(i = 0; i < 2; i++)
    {
        printf("%d %s %s %d %d\n",sw[i].id,sw[i].first_name,sw[i].last_name,sw[i].st.age,sw[i].st.status);
    }

我的数据结果:

Before sorting:
1 John Smith 33 1
2 Jack Smith 18 1
After sorting:
2 Jack Smith 18 1
1 John Smith 33 1