2016-03-13 31 views
-3

我這裏有這個功能,讀取文件中的格式:輸入文件中讀取與怪異字符

(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線可能是代碼中的問題嗎?

+2

「我知道我的代碼很混亂,請原諒我。」你知道這很麻煩,然後修復它,不要道歉。 –

+0

'fscanf(fp,「%d [^ \ n]」,&birthday);'→'fscanf(fp,「%d」,&birthday);' –

回答

2

這是你的問題:

strncpy(location, line, sizeof(line)); 

有了這條線,你從(初始化!)陣列line複製到location。由於line未初始化,其內容爲不確定,您將得到未定義的行爲

相反,您應該「清除」location數組,以便稍後在循環中添加它。這是最簡單的定義location陣列時完成:

char location[100] = { 0 }; 

這將設置爲零的location所有元素,它是一個字符串結束。

+0

我以爲是這樣!我應該使用另外的功能嗎我的目標是實際擦拭陣列,使其不包含以前的數據。 – Xirol

+0

非常感謝! – Xirol