i-Sam

Month

December 2011

15 posts

Dec 29, 2011171,745 notes
Dec 28, 201110 notes
Dec 28, 201131 notes
Dec 28, 2011117 notes
Dec 28, 201195 notes
Dec 28, 201120 notes
Dec 28, 201141 notes
Dec 28, 201110 notes
Dec 28, 2011156 notes
Dec 28, 201162 notes
Dec 28, 201127 notes
Dec 28, 201123 notes
Dec 28, 2011105 notes
Dec 18, 201116 notes
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);
}
Dec 14, 201125 notes
#code #snippit #programming #c #language #files #help
Next page →
2011 2012
  • January 17
  • February 5
  • March 40
  • April
  • May
  • June
  • July
  • August
  • September
  • October
  • November
  • December
2010 2011 2012
  • January 7
  • February 1
  • March 1
  • April 1
  • May 8
  • June 8
  • July 6
  • August 10
  • September 2
  • October 1
  • November 2
  • December 15
2010 2011
  • January
  • February 4
  • March 9
  • April 2
  • May 5
  • June 5
  • July 4
  • August 7
  • September 2
  • October 1
  • November
  • December 6