将txt文件的每个char存储到数组中

我想要做的是读取一个txt文件并存储在一个带有char成员的结构中,我的文件的每一个字符。

这是我的代码:

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,但我无法使用它。

谢谢。

从代码的外观来看,您试图存储某个字符在文件中出现的次数。 为此,我建议您编写一个哈希函数并将其存储到哈希表中。 这将更快,更不容易出错。

 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; } 

您没有为charClass结构分配足够的空间。 尝试用这个替换malloc:

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

另外,我不确定你使用索引i索引的是什么。 你似乎没有创建一个charClasses数组……?

您可以通过初始化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*/ }