Reading word by word from text file in C

code4life picture code4life · Oct 13, 2014 · Viewed 16.7k times · Source

I am very new to C. I am trying to read the words from a file which contains lots of not alpha characters. My input file looks something like this %tOm12%64ToMmy%^$$6 and I want to read tom first and then put tom in my data structure and then read tommy and put that in my data structure all in lowercase. This is what I have tried until now. All my other code works as I have manually sent the parameters to the methods and there are no errors. This is what I have tried to read the words from the file. A word can be of 100 characters max. Can someone help me understand the logic and possibly this code.I am very lost.Thank You!

void read(FILE *fp)
{
  FILE *fp1 = fp;
  char word[100];
  int x;
  int counter = 0;

  while ((x = fgetc(fp1)) != EOF)
  {
     if (isalpha(x) == 0)
     {
        insert(&tree,word);
        counter = 0;
     }
     if (isalpha(x) != 0)
     {
        tolower(x);
        word[counter] = x;
        counter++;
     }
  }
  rewind(fp1);
  fclose(fp1);
}

Answer

BLUEPIXY picture BLUEPIXY · Oct 14, 2014
char *getWord(FILE *fp){
    char word[100];
    int ch, i=0;

    while(EOF!=(ch=fgetc(fp)) && !isalpha(ch))
        ;//skip
    if(ch == EOF)
        return NULL;
    do{
        word[i++] = tolower(ch);
    }while(EOF!=(ch=fgetc(fp)) && isalpha(ch));

    word[i]='\0';
    return strdup(word);
}
void read(FILE *fp){
    char *word;
    while(word=getWord(fp)){
        insert(&tree, word);
    }
    //rewind(fp1);
    fclose(fp);
}