thatboinick
thatboinick

Reputation: 11

How to do I read every newline in a file at once?

I am trying to write a program that inputs a integer, reads a file with multiple lines of text and numbers. The file might contain something like this, File.txt

Daisy Feed Game Egg Clown Car Daisy Fowl 11 4

Fowl Apple 14 11 18 13 Dairy Clown File 5

The program would take a integer like 10, and read the file up to 10 words and output the index of the number it reads, EX

./a.out 10 File.txt

Apple Clown

What we did was read the first 10 words, and if the word was a number it printed the indexed word at that number. Ex File[11], and File[4].

My problem is that my program works great as long as im only working with one line at a time, when I try to index the file at File[11], instead of Apple, I get a segmentation fault. I am very stuck on how to fix this.

Here is my code,

    int main(int argc, char const *argv[])
    {
    int n = atoi(argv[1]);

    FILE *fp;

    char word[256];

    int indexes[n];

    char *words[n];
 
    for(int i = 0;i<n;i++) {
    words[i] = (char *)malloc(sizeof(char) * 256);
    indexes[i] = -1;
    }

    fp = fopen(argv[2],"r");

    int i = 0,j = 0;
    while(fscanf(fp,"%s",word)) {
    strcpy(words[i++],word);
    if(word[0] >= '0' && word[0] <= '9') {
    indexes[j++] = atoi(word);
    }

    if(i == n) {
    break;
    }
    }
    fclose(fp);
    // prints the words in the indexes
    for(i = 0;i<j;i++) {
    printf("%s ",words[indexes[i]]);
    } 

I tried to put every line into a long string but I was unable to get this to work properly.

Upvotes: 0

Views: 49

Answers (0)

Related Questions