目前是用 fscanf 和动态来写,读一个写一个这样
不过这样变成每读一次都要 realloc 一次感觉不太好
请问有什么可以让 fscanf 的指标往回的方式吗?
还是每读一次就 realloc 一次就好了呢?
realloc 如果原本位置不够会给一个新的地址
把东西复制过去并且 free 掉原本的空间对吧
可是 realloc 完之后前面两个数据都会跑掉不知道为什么
http://i.imgur.com/7GVK0lz.jpg
抱歉问题颇多,麻烦各位了
typedef struct {
int start_i, start_j; // 起点座标
int end_i, end_j; // 终点座标
int direction; // 边的指向
int internal; // 内部方向
}coordinate;
int main(int argc, char *argv[]) {
FILE *fp;
char str[30] = "f1.txt";
fp = fopen(str, "r");
if (NULL == fp) {
printf("开档失败\n");
}
int i = 0;
int j = 0;
int coordinate_i, coordinate_j;
char str2[60];
coordinate *qwe = (coordinate*)malloc(10 * sizeof(coordinate));
coordinate *qwer;
while (strcmp("POLYGON", str2) != 0) {
fscanf(fp, "%s", &str2);
printf("%s\n", str2);
}
i = 4;
fscanf(fp, "%d %d %d %d", &(*qwe).start_i, &(*qwe).start_j, &(*qwe).end_i, &(*qwe).end_j); // 输入边 1. 的起点和终点座标
(*(qwe + 1)).start_i = (*qwe).end_i;
(*(qwe + 1)).start_j = (*qwe).end_j;
printf("边1. (%d,%d)到(%d,%d)\n", (*qwe).start_i, (*qwe).start_j, (*qwe).end_i, (*qwe).end_j);
fscanf(fp, "%d %d", &(*(qwe + 1)).end_i, &(*(qwe + 1)).end_j);
(*(qwe + 2)).start_i = (*(qwe + 1)).end_i;
(*(qwe + 2)).start_j = (*(qwe + 1)).end_j;
printf("边2. (%d,%d)到(%d,%d)\n", (*(qwe + 1)).start_i, (*(qwe + 1)).start_j, (*(qwe + 1)).end_i, (*(qwe + 1)).end_j);
fscanf(fp, "%d %d", &(*(qwe + 2)).end_i, &(*(qwe + 2)).end_j);
(*(qwe + 3)).start_i = (*(qwe + 2)).end_i;
(*(qwe + 3)).start_j = (*(qwe + 2)).end_j;
printf("边3. (%d,%d)到(%d,%d)\n", (*(qwe + 2)).start_i, (*(qwe + 2)).start_j, (*(qwe + 2)).end_i, (*(qwe + 2)).end_j);
fscanf(fp, "%d %d", &(*(qwe + 3)).end_i, &(*(qwe + 3)).end_j);
printf("边4. (%d,%d)到(%d,%d)\n", (*(qwe + 3)).start_i, (*(qwe + 3)).start_j, (*(qwe + 3)).end_i, (*(qwe + 3)).end_j);
qwer = qwe;
while ((*qwe).start_i != (*(qwe + i - 1)).end_i || (*qwe).start_j != (*(qwe + i - 1)).end_j) {
i += 1;
for (j = 0; j < i; j++) {
printf("边%d. (%d,%d)到(%d,%d)\n", j + 1, (*(qwe + j)).start_i, (*(qwe + j)).start_j, (*(qwe + j)).end_i, (*(qwe + j)).end_j);
}
printf("\n");
qwe = (coordinate *)realloc(qwe, i); // 这绝对不是好方法(每个新座标都realloc一次),之后再一起改掉(提醒一下)
for (j = 0; j < i; j++) {
printf("边%d. (%d,%d)到(%d,%d)\n", j + 1, (*(qwe + j)).start_i, (*(qwe + j)).start_j, (*(qwe + j)).end_i, (*(qwe + j)).end_j);
}
printf("\n");
fscanf(fp, "%d %d", &(*(qwe + i - 1)).end_i, &(*(qwe + i - 1)).end_j);
(*(qwe + i - 1)).start_i = (*(qwe + i - 2)).end_i;
(*(qwe + i - 1)).start_j = (*(qwe + i - 2)).end_j;
printf("边%d. (%d,%d)到(%d,%d)\n\n", i , (*(qwe + i - 1)).start_i, (*(qwe + i - 1)).start_j, (*(qwe + i - 1)).end_i, (*(qwe + i - 1)).end_j);
}
system("pause");
return 0;
}