Home > database >  How can I dynamically allocate memory for a string read from a txt file in C ? More specifically, ho
How can I dynamically allocate memory for a string read from a txt file in C ? More specifically, ho

Time:11-18

I have a struct Art. I want to create a function to read a txt file into a vector of pointers to structs.

struct art {
    char *author;
    char *title;
};
typedef struct art Art; 

Art *readFile(Art **vec, FILE* file);

int main(void){
    FILE *file = fopen("filename.txt","r");
    if (file==NULL){
        printf("Failed");
        return NULL;
    }
    Art **vec = (Art**)malloc(150*sizeof(Art*));
    vec = readFile(vec,file);
    return 0;
}

Art *readFile(Art **vec, FILE* file){
    // I want to allocate memory for each of the strings, they have to be of size 80.

    while(fscanf(file, "%[^;];%[^;];", x, y) ==2); //the author and title are separated by semicolons in the file
    

    return vec;
}

What should I put in the x and y values???

CodePudding user response:

If you know they are no longer than 80 chars, use local arrays: char x[81], y[81]; Then you can duplicate them in the struct with strdup or malloc strcpy.

struct art {
    char *author;
    char *title;
};
typedef struct art Art; 

int readFile(Art **vec, int array_length, FILE* file);

int main(void) {
    FILE *file = fopen("filename.txt","r");
    if (file==NULL){
        printf("Failed");
        return NULL;
    }
    Art **vec = malloc(150 * sizeof(Art *));
    int num_read = readFile(vec, 150, file);
    return 0;
}

int readFile(Art **vec, int array_length, FILE* file)
{
    int count = 0;
    char author[81], title[81];

    while (fscanf(file, "            
  • Related