Having trouble with file I/O and string arrays

The file I'm reading from just has names separated by a line. What happens is the program tries to print the contents of line_array, and it will print out about 20 of the last line in the txt file.

#include <stdio.h>

FILE* fp;

int main(){

    char* line;
    const char* line_array[255];
    int i= 0;
    int b =0;
    fp = fopen("noob.txt","r");

    while(fgets(line,255,fp)){
        line_array[i]=line;
        printf("%s",line);
        printf("%s",line_array[i]);
        i++;
    }

    for(;b<i;b++){
        printf("%s",line_array[b]);
    }
    fclose(fp);
    return 0;
}

Upvotes: 1

Views: 31

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134366

The first issue, in your code,

while(fgets(line,255,fp))

line is used uninitialized. There is no memory allocated to line. It invokes undefined behavior.

Then, you did not check for the success of fopen() before using the returned file pointer. Again, possible UB.

And finally, by saying

 line_array[i]=line;

what you did is to store the line itself to all the occurrences of line_array[n], so for the later printf() loop, the latest content of line is being printed over and over again.

Solution(s):

  • Allocate memory to line or use a fixed length-array.
  • Check for the success of fopen()before using the returned pointer.
  • Allocate memory to each line_array[n] and use strcpy() to copy the content. Ottherwise, you can directly use strdup(), too.

Upvotes: 1

Related Questions