-1
void words(FILE *in,char *current_word){
    char punctuation[]= ". ,;:*!?'-\n\0\r";
    char c = fgetc(in);
    int i = 0;
    while(strchr(punctuation,c) == NULL){
        current_word[i] = c;
        i++;
        c = fgetc(in);
    }
    current_word[i] = '\0';

}

int main(){


    FILE *in = fopen("file.txt","r");

    while(!feof(in)){
        char current_word[30];
        char *cw = current_word;
        words(in,cw);
        printf("%s",current_word);
    }
}    

So I read from a file, create my own array current_word, make a pointer to that array so I edit it later. I call the words function that has an array of punctuation marks. While none of the characters I take from the file are any of these punctuation marks I add them to the current_word array which is pointed to by the pointer I passed into the function words.

I probably missing some knowledge on pointers.

This is continuously giving me the error Segmentation fault

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Charana
  • 1,074
  • 1
  • 13
  • 26

1 Answers1

1

Among other problems, this is likely a duplicate of this question:

Why is “while ( !feof (file) )” always wrong?

feof() does not return non-zero until EOF is actually hit. So you call words():

void words(FILE *in,char *current_word){
    char punctuation[]= ". ,;:*!?'-\n\0\r";
    char c = fgetc(in);  /* feof() returns int, not char */
    int i = 0;

    /* following loop will never stop as EOF isn't in the string */
    while(strchr(punctuation,c) == NULL){
        current_word[i] = c;
        i++;
        c = fgetc(in);
    }
    current_word[i] = '\0';

}

Each call to fgetc() returns EOF. And EOF is an int value.

But you've defined char c; instead of the proper int c;.

Community
  • 1
  • 1
Andrew Henle
  • 32,625
  • 3
  • 24
  • 56