Pawel Wasiliuk Pawel Wasiliuk - 1 month ago 15
C Question

Reading from a file with fopen: is a char** returned correctly?

I have a problem with the getting correct data in a char* content. I want to read from file its content, fill my buffer with it, and be able to deference char** content to the address of buffer. And then get its data from char* content in main... What am I doing wrong so far?

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

void load(FILE* file, char** content, size_t* length);

int main()
{
FILE* file = fopen("file.txt", "r");

char* content;
size_t length = 0;

load(file, &content, &length);

printf("%s\n", content);
printf("%lu\n", length);
}

void load(FILE* file, char** content, size_t* length)
{
char buffer[30];

fgets(buffer, 30, file);
*content = buffer;
*length = strlen(buffer);

}

Answer

Your load function should look something like this:

void load(FILE* file, char** content, size_t* length)
{
    char *buffer;
    buffer = (char*)malloc(30*sizeof(char));

       fgets(buffer, 30, file);
       *content = buffer;
       *length = strlen(buffer);

}
Comments