Read the entire contents of a file to c char *, including new lines

后端 未结 4 1930
孤城傲影
孤城傲影 2021-01-25 13:53

I\'m looking for a cross platform (Windows + Linux) solution to reading the contents of an entire file into a char *.

This is what I\'ve got now:



        
4条回答
  •  日久生厌
    2021-01-25 14:20

    I've got this:

    ssize_t filetomem(const char *filename, uint8_t **result)
    { 
        ssize_t size = 0;
        FILE *f = fopen(filename, "r");
        if (f == NULL) 
        { 
            *result = NULL;
            return -1;
        } 
        fseek(f, 0, SEEK_END);
        size = ftell(f);
        fseek(f, 0, SEEK_SET);
        *result = malloc(size);
        if (size != fread(*result, sizeof(**result), size, f)) 
        { 
            free(*result);
            return -2;
        } 
    
        fclose(f);
        return size;
    }
    

    Meaning of return value:

    • Positive or 0: successfully read the file
    • minus one: couldn't open file (possibly no such file)
    • minus two: fread() failed

提交回复
热议问题