简体   繁体   中英

Segmentation fault when reading words from a file

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

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

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