December 2011
15 posts
C File Helper Snippit
I’ve been writing some code in pure C for the past few days, and been making a lot of lower level “helper” functions of a kind.(Specifically more related to libcurl however.) So I figured I might as well share some snippits every now and then. :)
Here are two helper functions, for raw files. They make it easy to get a file’s size, and it’s data.
I might have more snippits to share as I continue working on this little project of mine. I might even open source the libcurl helper functions I’m working on. I’m writing this stuff because a friend requested me to make a certain plugin for a certain popular app. I want a really good code base for communicating with web service APIs, so I’m doing one myself. BAM!
long fileSize(FILE *handle)
{
//get current loc, so we can return it there when we're done
long currentLoc = ftell(handle);
//get the size
fseek(handle, 0, SEEK_END);
long size = ftell(handle);
//now put the location back to where it was
fseek(handle, currentLoc, SEEK_SET);
return(size);
}
char *fileData(FILE *handle)
{
//get the current location, so we can return there when done
long currentLoc = ftell(handle);
//get size & get to the start of the file
rewind(handle);
long size = fileSize(handle);
char *data = (char *)malloc(sizeof(char)*size);
if(data == NULL) //make sure we were able to alloc the memory
return(NULL);
size_t result = fread(data, sizeof(char), size, handle);
if(result != size) //make sure we read it all
return(NULL);
//now just return back to the old location...
fseek(handle, currentLoc, SEEK_SET);
return(data);
}