Reading lines from c file and putting the strings into an array

15,002

You need to change

programs[i]=line; 

to

programs[i]=strdup(line); 

Otherwise all pointers in the programs array will point to the same location (that is line).

BTW: if files.txt contains more than 50 lines, you will run into trouble.

Share:
15,002
user3192682
Author by

user3192682

Updated on June 07, 2022

Comments

  • user3192682
    user3192682 almost 2 years

    I'm trying to add each line of a c file into an array. The contents of files.txt is

    first.c
    second.c
    third.c
    fourth.c
    

    I want my code to print each of these lines, add the line to my array, and then print out each entry in my array. Right now it is doing the first part correctly but it is only adding fourth.c to the array. Can someone tell me what is wrong with my code?

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void) {
        int i=0;
        int numProgs=0;
        char* programs[50];
        char line[50];
    
        FILE *file;
        file = fopen("files.txt", "r");
    
        while(fgets(line, sizeof line, file)!=NULL) {
            //check to be sure reading correctly
            printf("%s", line);
            //add each filename into array of programs
            programs[i]=line; 
            i++;
            //count number of programs in file
            numProgs++;
        }
    
        //check to be sure going into array correctly 
        for (int j=0 ; j<numProgs+1; j++) {
            printf("\n%s", programs[j]);
        }
    
        fclose(file);
        return 0;
    }