[英]input file being read with weird characters
我在這里有這個功能,它以以下格式讀取文件:
(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
我假設我的 'while(fgets...' 對於該位置一定有問題,但我不知道為什么。奇怪的字符意味着它從我沒有分配的地址或類似的地址讀取數據對嗎?如果我聽起來很混亂,我很抱歉。
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 行可能是代碼中的問題嗎?
這是你的問題:
strncpy(location, line, sizeof(line));
使用這一行,您可以將(未初始化! )數組line
復制到location
。 因為line
未初始化,它的內容是不確定的,你會得到未定義的行為。
相反,您應該“清除” location
數組,以便稍后在循環中附加到它。 定義location
數組時最容易做到這一點:
char location[100] = { 0 };
這會將location
所有元素設置為零,即字符串終止符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.