2012-10-15 59 views
1

我想要做的是讀取一個txt文件並將其存儲在一個char成員的結構中,每個字符都是我的文件。將txt文件的每個字符存儲到數組中

這裏是我的代碼:

typedef struct charClass { 
    char simbolo; 
    int freq; 
} charClass; 

這是主要的顯著部分:

input = fopen("testo1.txt", "r"); 

fseek(input, 0, SEEK_END); //Mi posiziono alla fine del file 
int dim = ftell(input); //Ottengo il puntatore corrente (n char) 
fseek(input, 0, SEEK_SET); //Rimetto il puntatore all'inizio del file 

char tmpChar; 
charClass *car; 
car = malloc(dim*sizeof(int)); 

int i = 0; 

while (!feof(input)) { 
    tmpChar = getc(input); 
    car[i].simbolo = tmpChar; 
    printf("\n%c", car[i].simbolo); 
    car[i].freq++; 
    i++; 
} 

墜毀。

我嘗試在網上搜索,但沒有找到答案。

我試過也使用fscanf和strcpy,但我無法得到它的工作。

謝謝。

回答

1

從代碼的外觀來看,您試圖存儲特定字符在文件中出現的次數。爲此,我建議您編寫一個哈希函數並將其存儲到哈希表中。這會更快,更不容易出錯。

struct hash_blob{ 
    char character; 
    int freq; 
}; 
static struct hash_blob hashTable[52]; /*[A-Za-z]*//*Extend this size to include special characters*/ 

void setZero() 
{ 
    int i = 0; 
    for(i = 0; i < 52; i++) hashTable[i].freq = 0; 
} 
int compute_hash(char ch) 
{ 
    if(ch >= 'A' && ch <= 'Z'){ 
     return ch-'A'; 
    } 
    if(ch >= 'a' && ch <= 'z'){ 
     return ch - 'a' + 26; 
    } 
} 

void add_hash(char ch) 
{ 
    int loc = compute_hash(ch); 
    hashTable[loc].character = ch; 
    hashTable[loc].number++; 
} 

int main(int argc, char *argv[]) 
{ 
    int ch; 
    char filename = "testo1.txt"; 
    FILE *f = (FILE *)fopen(filename,"r"); 
    if(f == NULL)return 1; 
    while((ch = getc(f)) != EOF){ 
     add_hash(ch); 
    } 
    for(ch = 0; ch < 52; ch++) 
    { 
     printf("The number of times %c appears in the file is: %d times\n",hashTable[ch].character, hashTable[ch].number); 
    } 
    return 0; 
} 
2

你沒有爲你的charClass結構分配足夠的空間。嘗試用這個替換malloc:

car = malloc(dim * sizeof(charClass)); 

此外,我不知道你索引到什麼,使用索引我。它似乎並沒有創建一個charClasses數組...?

0

您可以通過初始化char數組並使用fgets()函數輕鬆完成此操作。

char buffer[50]; 
while(fgets(buffer,50,fp))//fp is the file pointer 
    { 
/*Code for checking buffer elements and you can store them in your chosen array*/ 
    } 
相關問題