I'm trying to write a function in C that reads a file into char array passed to it.
void read_file(char* path, char** bufptr, char* buffer){
/* open the file, and exit on errors */
FILE *fp = fopen(path, "r");
if(fp == NULL){
perror("Failed to open file");
exit(1);
}
/* figure out how long the file is to allocate that memory */
fseek(fp, 0, SEEK_END);
long length = ftell(fp);
rewind(fp);
/* allocate memory */
*bufptr = realloc(*bufptr, length+1);
fread(buffer, length, 1, fp);
buffer[length] = 0;
}
The idea is that I would use it something like this:
int main(int argc, char** argv){
char* somestring = malloc(1024);
core_read_file("/some/file/path", &somestring, somestring);
printf("In main(): %s\n", somestring);
free(somestring);
return 0;
}
However whenever I use it, while the program compiles, the printf prints nothing to the console. I'm starting out and kind of understand the idea of "indirection" to a very very basic degree, but can someone explain to me why my code doesn't work the way I expect it to, and how I should go about implementing this function.
(This isn't a homework assignment so any solution or method that works is perfect)
bufferargument toread_file. Simply write*bufptranywhere you're currently writingbuffer, e.g.fread(*bufptr, ...); (*bufptr)[length] = 0rbmode. Also the usual "you're overwriting the old pointer inrealloc" complaint...realloc, could youmallocthe right amount initially and return that?