【发布时间】:2017-01-30 02:48:28
【问题描述】:
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
对于程序,我有一个名为 arr[] 的 char * 数组,我试图按字母顺序对其进行排序,但没有运气这样做,所以在最后运行 for 循环时它什么也不做。我想用 arr[] 保留 offset[],因为我需要 char 代码和文件的偏移量
typedef struct country {
char code_name[4];
char name[45];
int population;
float life_expect;
}country;
country data[240];
int main(void) {
char *swap;
int a=0,c=0,d=0,n=0;
int cmp = 1;
这里是arr[]
char *arr[239];
size_t offset[239];
char *ptr;
int i = 0;
int temp;
char buf[512];
char *token;
char buf_write[10000];
size_t nbytes_written;
size_t t_nbytes;
FILE *fptr;
fptr = fopen("AllCountries.dat", "r");
int wptr;
wptr = open("BinaryAllCountries.dat", O_RDWR);
FILE *rptr;
rptr = fopen("BinaryAllCountries.dat", "r");
do {
if (fgets(buf, 512 , fptr)){
//printf("%s\n",buf);
token = strtok(buf,",;");
while (token != NULL){
token = strtok(NULL, ",;");
if (temp == 0){
strcpy(data[i].code_name, token);
nbytes_written = write(wptr, token, strlen(token));
t_nbytes = t_nbytes + nbytes_written;
//printf("code_name: %s\n", data[i].code_name);
}
if (temp == 1){
strcpy(data[i].name, token);
cmp = strcmp(data[i].name, "Virgin Islands");
nbytes_written = write(wptr, token, strlen(token));
t_nbytes = t_nbytes + nbytes_written;
//printf("name: %s\n", data[i].name);
}
if (temp == 6){
data[i].population = atoi(token);
nbytes_written = write(wptr, token, strlen(token));
t_nbytes = t_nbytes + nbytes_written;
//printf("population: %i\n", data[i].population);
}
if (temp == 7){
data[i].life_expect = atof(token);
nbytes_written = write(wptr, token, strlen(token));
t_nbytes = t_nbytes + nbytes_written;
//printf("life expectancy: %f\n", data[i].life_expect);
}
temp = temp + 1;
}
arr[i] = data[i].code_name;
offset[i] = t_nbytes;
/*
printf("%s\n",arr[i]);
printf("%lu\n", offset[i]);
*/ printf("--------\n");
i = i + 1;
temp = 0;
}
}while (!feof(fptr));
这是我尝试对数组进行排序的地方,但没有任何反应,数组保持不变
for (c = 0 ; c < 10; c++){
for (d = 0 ; d < 238; d++){
if (arr[d] > arr[d+1]){
swap = arr[d];
arr[d] = arr[d+1];
arr[d+1] = swap;
}
}
}
for (i = 0; i <239; i++){
printf("%s\n",arr[i]);
}
这是 arr[] 中的一些输出的样子,您可以看到它没有排序
DZA 前 本 BWA 物联网 博鳌亚洲论坛 BDI CMR 每次观看费用 CAF TCD 通讯 重心 鳕鱼 CIV 大疆 埃及 GNQ ERI 以太坊 瞎扯 专线小巴 GHA 杜松子酒 GNB 肯 伦敦交响乐团 LBR LBY 千年发展目标 MWI MLI 捷运
【问题讨论】:
-
qsort()有什么问题 -
我想保留与 char arr[] 关联的 offset[] 数组,因为我需要它们作为文件
-
然后定义一个带有
char *和size_t(或off_t,如果是文件偏移量)成员的结构,使用此类结构的数组,并使用@987654330对其进行排序@ 和你自己的比较函数。 man 3 bsearch 手册页有一个 qsorting 结构数组的示例。 -
所以我可以在我的 stuct 中添加一个 size_t 然后我可以 qsort 吗?