我想从具有类似行的文本文件中读取(其中大约200个具有一些空行,然后)。 我知道某些东西可能是未初始化的,但我对它是什么是空白的。我现在想要做的只是从文件中读取并打印到终端窗口中。从文件读取结构到终端,分段错误
我真的希望你能帮助我! 谢谢。的文本文件中的几行
例子:
Fre 19/07 18.30 AGF - FCM 0 - 2 9.364
Lor 20/07 17.00 VFF - RFC 2 - 2 4.771
Son 21/07 14.00 OB - SDR 1 - 1 7.114
我的结构是这样的:
struct match {
char weekday[MAX_NAME_LEN];
int day;
int month;
int hours;
int minutes;
char home_team[MAX_NAME_LEN];
char away_team[MAX_NAME_LEN];
int home_team_goals;
int away_team_goals;
int spectators_thds;
int spectators_hdrs;
};
我read_file
功能如下:
void read_file(struct match *match) {
FILE *fp;
int i;
fp = fopen("superliga-2013-2014", "r");
while (!fp) {
error("Cannot open file.");
}
struct match *matches = (struct match *) malloc(sizeof(match) * MAX_MATCHES);
while(!feof(fp)) {
fscanf(fp, " %s %i/%i %i.%i %s - %s %i - %i %i.%i \n",
matches[i].weekday, &matches[i].day, &matches[i].month, &matches[i].hours,
&matches[i].minutes, matches[i].home_team, matches[i].away_team,
&matches[i].home_team_goals, &matches[i].away_team_goals,
&matches[i].spectators_thds, &matches[i].spectators_hdrs);
}
fclose(fp);
free(fp);
}
而且我main
功能如下所示:
int main(int argc, char *argv[]) {
int i;
struct match *matches;
void read_file(struct match *matches);
for (i = 0; i < MAX_MATCHES; ++i) {
printf(" %s %i/%i %i.%i %s - %s %i - %i %i.%i ",
matches[i].weekday, matches[i].day, matches[i].month, matches[i].hours,
matches[i].minutes, matches[i].home_team, matches[i].away_team,
matches[i].home_team_goals, matches[i].away_team_goals,
matches[i].spectators_thds, matches[i].spectators_hdrs);
}
return 0;
}
它编译没有问题,但我试图运行它时得到一个Segmentation fault
。然后我用Valgrind的,它给了我这个消息:
==12799== Use of uninitialised value of size 8
==12799== at 0x4007B8: main (in /home/dradee/Dropbox/UNI/Programmering/C/readfile)
==12799==
==12799== Invalid read of size 4
==12799== at 0x4007B8: main (in /home/dradee/Dropbox/UNI/Programmering/C/readfile)
==12799== Address 0x34 is not stack'd, malloc'd or (recently) free'd
==12799==
==12799==
==12799== Process terminating with default action of signal 11 (SIGSEGV)
==12799== Access not within mapped region at address 0x34
==12799== at 0x4007B8: main (in /home/dradee/Dropbox/UNI/Programmering/C/readfile)
http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong – 2015-02-10 22:17:35
确定MAX_MATCHES是足够大的为您的文件? – m0skit0 2015-02-10 22:21:48