C returning const char pointer or char pointer from a function
<p>I wanted to understand this a bit better so I am asking here. I write a function that reads a file and returns the contents as a string. It is currently implemented as returning a <code>char*</code> because it seems easier but I am wondering if this is the correct approach as a lot of C function prototypes that consumes <code>char</code> arrays consume them as <code>const char</code>. The reason that I say it's easier is because once you've read all the data if you want to return a <code>const char</code>, I have to create a new buffer that's the exact size and copy the data over there, instead of just reallocating the buffer down to the correct size and returning the pointer that was allocated on the heap.</p>

<p>My question, should the return value be a <code>const char*</code> or <code>char*</code>?</p>

<p>Here's a little code:</p>

<pre><code>char *get_resource(char **res, const char *filename) {
    size_t count = ((strlen(resource_dir) + strlen(filename) + 1));
    *res = calloc(count, sizeof(char));
    strncpy(*res, resource_dir, resource_dir_len);
    strncat(*res, filename, strlen(filename));
    return *res;
}
</code></pre>

<p>or this one:</p>

<pre><code>char *read_file(char **data, const char *file_path) {
    FILE *fp;
    size_t buffer = 4096;
    size_t index = 0;
    int ch;

    fp = fopen(file_path, "r");
    if (fp == NULL) {
        printf("failed to open file: %s\n", file_path);
        return "-1\0";
    }

    (*data) = calloc(buffer, sizeof(char));
    while (EOF != (ch = fgetc(fp))) {
        (*data)[index] = (char)ch;
        ++index;
        if (index == buffer - 1) {
            buffer = buffer * 2;
            data = realloc(data, buffer);
            if (data != NULL) {
                printf("buffer not large enough, reallocating %zu bytes to "
                       "load %s\n",
                       buffer, file_path);
            } else {
                printf("failed to realloc %zu bytes to load %s\n", buffer,
                       file_path);
            }
        }
    }
    (*data) = realloc((*data), (sizeof(char) * (index + 1)));
    (*data)[index] = '\0';

    fclose(fp);
    return *data;
}
</code></pre>