我正在尝试从txt文件中读取数据并将其插入到我拥有的结构中。我已经尝试过使用fscanf并且它会在我运行时编译但崩溃。我对编码很新,所以任何帮助都会受到赞赏。
数据格式如下
A1 6 30 4
A2 9 11 6
A3 9 30 7
A4 90 11 3
这是我到目前为止所拥有的
typedef struct Process
{
char name[3];
int arrivalTime;
int serviceTime;
int priority;
} Process;
int main(){
Process record[MAX];
int i, counter;
FILE *ifp;
ifp = fopen("data.txt","r");
if (ifp == NULL) {
fprintf(stderr, "Can't open input file in.list!\n");
exit(1);
}
while (EOF != fscanf(ifp, "%s %d %d %d", &record[i].name, &record[i].arrivalTime,
&record[i].serviceTime, &record[i].priority)){
i++;
counter;
}
fclose(ifp);
int j;
for (j = 0; j < counter; j++) {
printf(record[j].name, &record[j].arrivalTime,
&record[j].serviceTime, &record[j].priority);
}
}
答案 0 :(得分:0)
使用初始化了一些大小的缓冲区并从中读取数据。
char buffer[256];
while (EOF != fscanf(ifp, "%[^\n]\n", buffer)){
sscanf (buffer, "%s %d %d %d", record[i].name, &record[i].arrivalTime ,&record[i].serviceTime, &record[i].priority);
i++;
counter++;
}
使用以下方式打印:
for (j = 0; j < counter; j++) {
printf("%s %d %d %d \n", record[j].name, record[j].arrivalTime, record[j].serviceTime, record[j].priority);
}