#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>
这是我的结构,我用它来发送code_name和偏移字段到名为directory.dat的文件
typedef struct country {
char code_name[4];
char name[45];
int population;
float life_expect;
ssize_t offset;
}country;
country data[240];
static int
compmi(const void *m1, const void *m2)
{
struct country *mi1 = (struct country *) m1;
struct country *mi2 = (struct country *) m2;
return strcmp(mi1->code_name, mi2->code_name);
}
int main(void) {
char *swap;
int a=0,c=0,d=0,n=0;
int cmp = 1;
char *ptr;
int i = 0;
int temp;
char buf[512];
char *token;
char buf_write[10000];
ssize_t nbytes_written;
ssize_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");
这是我写给
的文件和文件指针
int dir_ptr;
dir_ptr = open("directory.dat", O_RDWR);
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;
}
data[i].offset = t_nbytes;
/*
printf("%s\n",arr[i]);
printf("%lu\n", offset[i]);
printf("--------\n");
*/
i = i + 1;
temp = 0;
}
}while (!feof(fptr));
qsort(data, sizeof(data)/sizeof(data[0]),sizeof(struct country),compmi);
当我尝试写入数据[i] .offset时,问题就在这里它没有做任何事情,文件只包含数据[i] .code_name
for (i = 0; i < 239; i++){
nbytes_written = write(dir_ptr, data[i].code_name, strlen(data[i].code_name));
nbytes_written = write(dir_ptr, (ssize_t *)data[i].offset, sizeof(data[i].offset));
}