繁体   English   中英

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

[英]Store each char of txt file into array

我想要做的是读取一个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,但我无法使用它。

谢谢。

您没有为charClass结构分配足够的空间。 尝试用以下方法替换malloc:

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM