【发布时间】:2018-04-30 11:44:37
【问题描述】:
我正在尝试从一个文本文件读取一个结构,该结构具有指向另一个结构的指针。
文本文件格式如下:
279288151 1 John Doe
002 1 30 04 2018
23189842 0 Jane Doe
0
282676381 1 Mark Examp
001 0 28 03 2018 03 04 2018
243897574 1 Joe Soap
003 2 14 04 2018 21 04 2018
这是我的 .h 文件:
#ifndef Clientes_h
#define Clientes_h
#include <stdio.h>
#include <stdlib.h>
#include "Alugueres.h"
#define ST_TAM 50
typedef struct info_cliente Cliente;
struct info_cliente{
char nome[ST_TAM];
long nif;
int n_alugueres;
int n_hist;
pAluga aluguer;
};
typedef struct aluga Aluguer, *pAluga;
typedef struct data DataIn, *pDataIn;
typedef struct data DaraEn, *pDataEn;
struct aluga{
int id_unico;
int estado;
pDataIn dataIn;
pDataEn dataEn;
pAluga prox;
};
struct data{
int dia;
int mes;
int ano;
};
Cliente* le_fich(char *nome, int *n);
#endif /* Clientes_h */
而我的 read_file 函数如下:
#include "Clientes.h"
Cliente* le_fich(char *nome, int *n){
FILE *f = fopen(nome, "r");
Cliente *aux;
int conta = 0;
if(!f){
printf("Error\n");
return NULL;
}
while(getc(f) != EOF){
aux = (Cliente*)malloc(sizeof(Cliente));
fscanf(f, "%ld %d %49[^\n]", &aux[conta].nif, &aux[conta].n_alugueres, aux[conta].nome);
if(aux[conta].n_alugueres != 0){
fscanf(f, "%d %d %d %d %d", &aux[conta].aluguer->id_unico,
&aux[conta].aluguer->estado, &aux[conta].aluguer->dataIn->dia,
&aux[conta].aluguer->dataIn->mes, &aux[conta].aluguer->dataIn->ano);
}
conta++;
}
return aux;
}
在 if 成功后尝试运行 fscanf 时出现 bad_access 错误(访问我的日期的结构指针时)。如果有人可以帮助我,将不胜感激。
【问题讨论】:
-
@Cyclonecode 我知道什么时候创建文件,但是一旦我到达文件末尾,我应该确定值。如果我在循环的开头放一个malloc,那会解决问题,然后用指针访问不同的字段吗?
-
while(getc(f) != EOF){丢失文件的第一个字符,'2'。 -
关于:
printf("Error\n");1) 错误消息应该输出到stderr,而不是stdout。 2) 还应输出系统认为发生错误的文本原因。建议:perror( "fopen failed" );专为此目的而创建 -
关于:
aux = (Cliente*)malloc(sizeof(Cliente));1) 任何堆分配函数的返回类型:malloccallocrealloc是void*,可以分配给任何指针。强制转换只会使代码混乱,使其更难以理解、调试等。 2) 始终检查 (!=NULL) 返回值以确保操作成功。如果不成功,调用perror()将你的错误信息和系统认为错误发生的原因文本输出到stderr -
强烈建议替换:`while(getc(f) != EOF){ aux = (Cliente*)malloc(sizeof(Cliente)); fscanf(f, "%ld %d %49[^\n]", &aux[conta].nif, &aux[conta].n_alugueres, aux[conta].nome);` with:
char buffer[1024]; while( fgets( buffer, sizeof buffer, f ) { call malloc() then use sscanf() to extract fieldsL &aux[conta].nif, &aux[conta].n_alugueres, aux[conta].nome)