我這裏有這個功能,讀取文件中的格式:輸入文件中讀取與怪異字符
(badgeno)
(name)
(location) // until it hits *
(birthday)
我添加了一個記錄到的txt文件,像這樣通過程序: 注:我在關閉該程序後檢查了該文件,並且在我再次打開該程序之前完全按照此方式寫入。
5432
Janna Wind
3321 Jupiter St
44324, Fi, CA
*
1990
然而,當我打開該程序,我打印記錄就顯示出來,如:
5432
Janna Wind
!34^&32()93321 Jupiter St
44324, Fi, CA
1990
當我檢查我保存它的txt文件進入關閉程序後,它看起來像這樣的:
5432
Janna Wind
!34^&32()93321 Jupiter St
44324, Fi, CA
*
1990
我猜想一定有什麼問題我「而(與fgets ...」的位置,但我想不出爲什麼奇怪的字符從地址意味着它的讀取數據。我沒有分配o這樣的事情是嗎?如果我聽起來很混亂,我很抱歉。
int readfile(struct test ** start, char filename[]){
FILE *fp = NULL;
fp = fopen(filename,"r");
int badgeno;
char fullname[45];
char location[100];
int birthday;
char line[80];
int opened = 1;
if (fp == NULL){
opened = 1;
} else {
opened = 0;
while (fscanf(fp, "%d\n", &badgeno) > 0) {
fgets(fullname, 45, fp);
strncpy(location, line, sizeof(line));
while (fgets(line, 80, fp)) {
if (strcmp(line, "*\n") == 0) {
line[0] = '\0';
break;
}
strncat(location, line, 79 - strlen(location));
}
fscanf(fp, "%d[^\n]", &birthday);
addRecord(start, badgeno, fullname, location, birthday);
}
}
fclose(fp);
return opened;
}
我知道我的代碼很混亂,所以請原諒。但是,當我重新打開程序時,可能會導致這些奇怪的字符出現。我的fgets線可能是代碼中的問題嗎?
「我知道我的代碼很混亂,請原諒我。」你知道這很麻煩,然後修復它,不要道歉。 –
'fscanf(fp,「%d [^ \ n]」,&birthday);'→'fscanf(fp,「%d」,&birthday);' –