2014-12-03 104 views
-1

正如標題所說,當調用beolvas()時,我會崩潰。你可能會得到我想要做的,這也很簡單。我正在使用mingw32 btw。感謝您提前提供任何幫助!C文件輸入fscanf問題(崩潰)

typedef struct 
{ 
    int kerSzam; 
    int voteCount; 
    char *lastName; 
    char *firstName; 
    char *party; 
} Vote; 

void beolvas(Vote t[], int *n) 
{ 
    FILE *in; 
    in = fopen("szavazatok.txt", "r"); 

    while(!feof(in)) 
    { 
     fscanf(in, 
       "%d %d %s %s %s\n", 
       &t[*n].kerSzam, 
       &t[*n].voteCount, 
       t[*n].lastName, 
       t[*n].firstName, 
       t[*n].party 
       ); 

     (*n)++; 
    } 

    fclose(in); 
} 

szavazatok.txt看起來是這樣的:

2 53 first last zed 
1 5 first last pet 
... 
+3

您必須爲結構的char *成員分配一些內存...... – 2014-12-03 20:06:56

+0

需要進一步的幫助嗎? – chux 2017-05-08 14:02:14

回答

1

正如@讓 - 巴蒂斯特Yunès評價說,需要爲字符串分配內存。

推薦測試fscanf()的結果。

void beolvas(Vote t[], int *n, int maxn) { 
    FILE *in; 
    in = fopen("szavazatok.txt", "r"); 
    if (in) { 
    char lastName[50]; 
    char firstName[50]; 
    char party[50]; 
    int cnt = 0; 

    // spaces not needed in format, but widths are very useful 
    while(*n < maxn && (cnt = fscanf(in, "%d%d%49s%49s%49s", 
     &t[*n].kerSzam, &t[*n].voteCount, lastName, firstName, party)) == 5) { 
     t[*n].lastName = strdup(lastName);  
     t[*n].firstName = strdup(firstName);  
     t[*n].party = strdup(party);  
     (*n)++; 
    } 

    fclose(in); 
    } 
} 

由於strdup()是非標準的,在這裏,如果需要的是一種實現。

char *strdup(const char *src) { 
    if (src) { 
    size_t size = strlen(src) + 1; 
    char *p = malloc(size); 
    if (p) { 
     return memcpy(p, src, size); 
    } 
    } 
    return 0; 
}