存储TXT文件的每一个字符到数组 [英] Store each char of txt file into array

查看:136
本文介绍了存储TXT文件的每一个字符到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是阅读一个struct一个txt文件,并存储为char成员,我的文件的每一个字符。

What I want to do is to read a txt file and store in a struct with a char member, every single char of my file.

下面是我的code:

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

坠毁。

我trye​​d在网络搜索,但我没有找到答案。

I tryed to search on Web but I didn't find an answer.

我trye​​d也使用的fscanf,和strcpy,但我不能得到它的工作。

I tryed to use also fscanf, and strcpy, but I couldnt get it work.

感谢。

推荐答案

从code的长相,你要保存一定的字符出现在文件的次数。对于这一点,我建议你到code散列函数,并把它存储到一个哈希表。这将是更快,更容易出错。

From the looks of your code, you're trying to store the number of times a certain character appears in a file. For that, I suggest you to code a hash function and store it into a hash table. That will be faster and less error prone.

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

这篇关于存储TXT文件的每一个字符到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆