gpt4 book ai didi

c - 不确定如何将整数从文件存储到 c 中的结构

转载 作者:行者123 更新时间:2023-11-30 19:10:17 24 4
gpt4 key购买 nike

我创建了两个结构来存储值。

struct pair {
int x_pos;
int y_pos;
};

struct coordinates_header {
int length;
struct pair data[1000];
};

typedef struct coordinates_header coordinates;
coordinates *coords;

然后我尝试使用存储文件中的数据

char line[max_read];
int x, y;
FILE *in_file = fopen(filename, "r");
int i = 0;
coordinates *new = (coordinates *)coords;
while (fgets(line,max_read,in_file) != NULL) {
sscanf(line,"%d %d", &x, &y);
new -> data[i].x_pos = x;
new -> data[i].y_pos = y;
i++;
}
new -> length = i;

然后我尝试打印出这些值

int print_struct(void *coords) {
coordinates *new = (coordinates *)coords;
for (int i = 0; i < new -> length; i++) {
printf("%d, %d\n", new->data[i].x_pos, new->data[i].y_pos);
}
return 0;
}

然后我遇到了段错误我想知道是否有人可以指出错误在哪里。我没有使用 void 的经验,但需要我将要使用的某些函数的结构具有灵 active 。

读取的文件将具有以下形式

100 30
50 200
.. ..

最佳答案

我相信您的代码中存在一些错误:

  • 您应该只声​​明一个结构成员坐标coords,而不是使用坐标 *coords;(它只是一个悬空指针,不指向内存中的任何位置)。
  • 您的代码中不需要 void* 指针。您最好使用坐标 *coords 来访问结构成员坐标 coords 的地址,而不是使用 void *coords 。
  • 您没有检查FILE *in_file的返回值,如果未正确打开,它可能会返回NULL
  • 检查 sscanf() 的结果总是好的,以防万一在一行上找不到两个 xy 坐标.

根据这些建议,您可以像这样编写代码:

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

#define NUMCOORDS 1000
#define MAXREAD 100

typedef struct {
int x_pos;
int y_pos;
} coords_t;

typedef struct {
coords_t coords[NUMCOORDS];
int length;
} coordinates_t;

void print_struct(coordinates_t *coordinates);

int main(void) {
coordinates_t coordinates;
char line[MAXREAD];
FILE *in_file;
int i = 0;

in_file = fopen("coords.txt", "r");
if (in_file == NULL) {
fprintf(stderr, "Error reading file.\n");
exit(EXIT_FAILURE);
}

while (fgets(line, MAXREAD, in_file) != NULL) {
if (sscanf(line, "%d %d", &coordinates.coords[i].x_pos,
&coordinates.coords[i].y_pos) != 2) {

fprintf(stderr, "two coordinates(x, y) not found.\n");
exit(EXIT_FAILURE);
}
i++;
}
coordinates.length = i;

print_struct(&coordinates);

fclose(in_file);

return 0;
}

void print_struct(coordinates_t *coordinates) {
int i;

for (i = 0; i < coordinates->length; i++) {
printf("%d, %d\n", coordinates->coords[i].x_pos, coordinates->coords[i].y_pos);
}
}

关于c - 不确定如何将整数从文件存储到 c 中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41646807/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com