I wrote an function which reads in an entire file into a string but it doesnt work

So, i need to read an entire file into a string in c, i dont know how big the file is gonna be. I wrote this function, but it doesnt work:

int slurp(char * filepath, char * outputfile) {  
    fp = fopen(filepath, "r");
    int success = 0;
    if (fp == NULL) {
        success = 1;
    }
    if (success == 0) {
        fseek(fp, 0, SEEK_END);
        outputfile = (char *) calloc(ftell(fp) + 1, sizeof(char));
        fread(outputfile, ftell(fp), sizeof(char), fp);
        fseek(fp, 0, SEEK_SET);
        outputfile[ftell(fp)] = '\0';
    }
    return success;
}

It doesnt get an error opening the file, but when i print out outputfile, i only get (null).

Why doesnt it work? Thanks.

I tried your suggestions and it still doesnt work:

int slurp(char * filepath, char * outputfile) {
    fp = fopen(filepath, "r");
    int success = 0;
    if (fp == NULL) {
        success = 1;
    }
    if (success == 0) {
        fseek(fp, 0, SEEK_END);
        size_of_file = ftell(fp);
        fseek(fp, 0, SEEK_SET);
        outputfile = (char *) calloc(size_of_file + 1, sizeof(char));
        fread(outputfile, size_of_file, sizeof(char), fp);
        outputfile[size_of_file] = '\0';
    }
    return success;
}

Upvotes: 1

Views: 55

Answers (1)

Milag
Milag

Reputation: 1986

Seek to the beginning before reading (reverse to this order):

fseek(fp, 0, SEEK_SET);
fread(outputfile, ftell(fp), sizeof(char), fp);

Upvotes: 1

Related Questions