【发布时间】:2014-12-03 10:03:04
【问题描述】:
我的代码又遇到问题了。
我想fscanfresult.txt 到带有链表的结构,但它不起作用;
我认为简单的链表一定够用了;
问题是:程序只写了第一行,没有别的。
result.txt 格式:
point name (for examples)
623 john
457 peter
312 chuck
etc.
代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct ranklist {
int point;
char* name;
struct ranklist *next;
} ranklist;
int how_many_records(FILE *fp){
char ch;
int line=0;
int status;
rewind(fp);
while((status=fscanf(fp, "%*d %*[^\n]%c", &ch))==1)
++line;
if(status != EOF){
++line;
}
rewind(fp);
return line;
}
int how_many_letter(FILE *fp){
int letter = 0;
long pos = ftell(fp);
//fscanf(fp, " %*[^\n]%n", &letter);
fscanf(fp, " %*s%n", &letter);
fseek(fp, pos, SEEK_SET);
return letter;
}
int main(void){
FILE *fp = fopen("result.txt","r");
int name_length;
int lines = how_many_records(fp);
ranklist *r = malloc(lines * sizeof(*r));
ranklist *first = r;
for ( r=first ;r != NULL; r = r->next){
fscanf(fp, "%d", &(r->point));
name_length = how_many_letter(fp);
r->name = malloc(name_length + 1);
fscanf(fp,"%s", r->name);
}
fclose(fp);
for ( r=first ;r != NULL; r = r->next){
printf("%d %s\n", r->point, r->name);
}
free(r);
return 0;
}
【问题讨论】:
-
I'm in trouble...我们不会向您提供明确的问题陈述,我们也一样。 -
阅读行时
fgets可能是更好的选择。 -
在
how_many_letter()中fscanf(fp, " %*s%n", &letter);没有提供足够的参数来写入数据。同样在how_many_records().
标签: c linked-list malloc