简体   繁体   中英

using char, cast to an int as array index to store frequency of “chars” in a textfile

Iam writing a simple program to store number of occurrence's of the various symbols in a text file. I am reading from this file using fgetc() and a file pointer. one char at a time. i set up my array outside my method like so

int frequency[MAX_SYMBOLS] = {0};

MAX_SYMBOLS is defined as being 255. I then read over the and try to count every time a particular character appears below is my method set_frequency()

void set_frequency()
{

    int count = 0;
    char c;
    FILE *fp = fopen("file.txt","r");

    while((c = fgetc(fp)) != EOF)
    {
      if(c != ' ' && c != '\n')
      {
             frequency[(int) c]++;
             count++;
      }
    }

    fclose(fp);

  }

iam currently getting a segmentation fault for this not entirely sure why? I think its an issue with the array index. or possibly the size of my file as it is rather large. If anyone can help that would be great as iam not great with c to be honest.

EDIT

the 'c' variable need to be an int not a char as that is what is returned from the fgetc() function. then I wont have to cast in the index value!!

In addition to the fact that EOF could not fit in a char , you have 2 potential problems:

  1. MAX_SYMBOLS is smaller than 255, that are the character you can find using plane ascii.
  2. char is a signed integer . If you read something > 0x7f it will be converted in a negative array index.

Try using an integer for reading to satisfy requirement for EOF. You'll also get guarantee that the code will never be negative, but in the range 0-255.

void set_frequency()
{

    int count = 0;
    int c;
    FILE *fp = fopen("file.txt","r");

    while((c = fgetc(fp)) != EOF)
    {
      if(c != ' ' && c != '\n')
      {
             frequency[c]++;
             count++;
      }
    }

    fclose(fp);

  }

If happens that you have to use chars for similar issues use cast to force unsigned values:

frequency[(int)(unsigned char) c]++;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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