2010-12-05 28 views
-1

我正在開發一個C中的鏈表。我正在從txt文件中獲取數據。但是,當我嘗試運行程序時,它給我的getc() 下面的代碼的分段錯誤,getc()中的分段錯誤

#include<stdio.h> 
#include<stdlib.h> 
struct node{ 
      char surname[100]; 
     int number[1o0]; 
     char name[100]; 
     struct node *next; 
     }; 
typedef struct node Node; 

int main() 
{ 
FILE *ifp; 
Node first ,*current; 
//current =&first; 
int i=0,j=0; 
int ch; 
char num[100],name[100]; 

ifp = fopen("tele.txt","r"); 

while (ch != EOF) 
{  
    while(i<4) 
    { 
     ch = getc(ifp); 
     num[i++] = ch; 
    } 
    num[i] = '\0'; 
    i=0; 
    while(ch !='\n') 
    {  
     ch = getc(ifp); 
     if(ch != '\t') 
     name[j++]=ch; 
    } 
    name[j] = '\0'; 
    //ch = '\0'; 

    printf("Number %s\nName %s\n ",num,name); 
    j=0; 

} 

fclose(ifp); 
} 

和我得到當我試圖運行的程序是錯誤,

程序收到信號SIGSEGV,分段故障。 0x0000003c0ee68dfa getc()from /lib64/libc.so.6

請在此引導我。 在此先感謝。


+1

它與segfault沒有關係,但是在與'EOF`比較之前應該初始化`ch`。只是偶然,可能會發生`ch`從開頭就等於`EOF`,程序甚至不會進入while循環。 – detunized 2010-12-05 22:45:43

+0

您需要檢查每個** getc()調用返回的EOF。以及檢查每個函數,比如`fopen()`可能會失敗。 – 2010-12-05 22:45:53

回答

6

最可能的原因是它無法打開文件。

在調用fopen("tele.txt","r")之後,請檢查ifp是否爲NULL。如果它是NULL,則errno會給出更多詳細信息(很多可能的原因,其中一些是:文件不存在,您沒有權限訪問它,或者您錯誤目錄)

也有幾個問題圍繞ch本身,可能是無關的崩潰:

  • ch沒有初始化,所以while (ch != EOF)可能會或可能不會進入[感謝@Dirk指出這出]。
  • while(ch !='\n')是有點狡猾,因爲如果你入侵EOF,你最終在一個無限循環。