0

Im trying to read a file into a struct which contains a char array as shown in the code below, however it gives an output of segmentation fault: 11. I have tried everything including using similar examples but it has done my head in.

My code is as below:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 1024

struct Raw_Word{
    char word[MAX_LENGTH];
    char filename [25];
    int length;
};

struct Final_Word{
    char word[MAX_LENGTH];
    int length;
    int amount;
};

struct Raw_Word raw_word[MAX_LENGTH];

int main(int argc, char* argv[]) {
if (argc > 10) {
        printf("Maximum of 10 files allowed");
        return 1;
    }

    int i = 0;
    int lines = 0;


    for (i = 1; i <= argc; i++) {
        FILE *fp = fopen(argv[i], "r");
while(fgets(raw_word[lines].word, MAX_LENGTH, fp)){
            //printf("%s", raw_word[lines].word);
        }
        fclose(fp);

    }

    for(int j = 0; j < lines; j++){
        printf("%s\n", raw_word[j].word);
    }

return 0;
}
1
  • 3
    As a general note, one of the best ways to find things like this is to first work out what line is causing the error. This can be done by putting in print statements or with gdb. Commented Dec 16, 2014 at 22:35

1 Answer 1

4

The line

for (i = 1; i <= argc; i++) 

is not right. You need to stop the index at argc-1.

for (i = 1; i < argc; i++) 

or

for (i = 1; i != argc; i++) 
Sign up to request clarification or add additional context in comments.

1 Comment

also, check fp != NULL before using it with fgets or any other function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.