你有一个文件,其中包含限定值的数组/列表(按“#”)文本,
123#john#smith
153#jane#smith
173#joe#doe
...
你可以精心字符数组数组来保存每个字段/列,假设您事先知道列有多大。但是你可能无法确定尺寸,而且这确实不是最好的方式。你可以定义一个结构,但同样的问题。
因此,为文件的每一行定义一个char *数组,您既可以指向数据的指针,也可以使用strdup为数据分配新的缓冲区。
#define MAXFIELDS (20) /*pick a sane value*/
char** /*return an array of pointers to char, char* fields[] */
parse_line(char* line,int* count)
{
int ndx;
char* p=line;
char* element;
char** fields = malloc(MAXFIELDS*sizeof(char*));
for(ndx=0; element = strtok(p,"#"); ++ndx) {
p=NULL;
/*either point directly at (a copy of) the string*/
fields[ndx] = element;
/*or use strdup to make a copy*/
fields[ndx] = strdup(element);
}
/*ndx contains number of elements*/
if(count) *count=ndx;
return(fields);
}
您可以定义行的最大数量从文件中读取,也可以使用链表(使用固定长度的数组在这里为简便起见)。
#define MAXROWS (100) /*pick a sane value*/
char** rows[MAXROWS];
void read_file()
{
FILE *file;
char name[100];
char *p;
int ndx=0; //rowcount
int fieldcount;
file=fopen("names.txt","r");
while(!feof(file)) {
fscanf(file,"%s\n",name);
/* either make a copy of the line here, or copy elements inside parse_line*/
p = strdup(name);
rows[ndx++] = parse_line(p,&fieldcount);
}
fclose(file);
}
您可以创建一个结构来表示每个“行”,然后创建一个这样的数组? –
@Nodeum:请学会像开发人员一样思考。不要说*它会给出错误*,显示你是如何做到的,并显示错误是什么。这是基本的东西。 Stackoverflow不是人们猜测你做了什么以及出了什么问题的地方。 –