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 char*
because it seems easier but I am wondering if this is the correct approach as a lot of C function prototypes that consumes char
arrays consume them as const char
. The reason that I say it's easier is because once you've read all the data if you want to return a const char
, 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.
My question, should the return value be a const char*
or char*
?
Here's a little 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;
}
or this one:
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;
}