Home > Back-end >  Copy lines from file to char *array[]?
Copy lines from file to char *array[]?

Time:02-22

Hi need a little bit of help here. I have a file with 5 lines and I want to put this lines into an array of type char *lines[5]; but I can't figure it out why the following isn't working.

#include <stdio.h>
#include <string.h>

int main(void) {
    FILE *fp = fopen("name.txt", "r");
    char *str;
    char *list[5];
    int i = 0;

    while (fgets(str, 100, fp) != NULL) // read line of text
    {
        printf("%s", str);
        strcpy(list[i], str);
        i  ;
    } 
}

CodePudding user response:

As the commenters stated, you need to create an array (which is nothing more than a space in the memory) of a sufficient size to store your string. One approach to solve your problems is the following, note the comments:

#include <stdio.h>
#include <string.h>

    int lines(FILE *file); //try to format the code according to some standard
    int main(void) {
        FILE *fp = fopen("name.txt", "r");
        char list[5][100]; //make sure you allocate enough space for your message

// for loop is more elegant than while loop in this case, 
// as you have an index which increases anyway.
// also, you can make sure that files with more than 5 lines 
// do not break your program.
        for(int i = 0; i<5 ;  i ) 
        {
            if(fgets(list[i], 100, fp) == NULL){
               break;
            }
            //list[i] is already a string, you don't need an extra copy
            printf("%s", list[i]);
        } 
    }
  • Related