X-Git-Url: https://secure.softndesign.org/git/?a=blobdiff_plain;f=file.c;h=786a895c1b8d9c6b896c3aa921b908079f8847d9;hb=refs%2Fheads%2Fmaster;hp=4a866b681bacc77a7aa3a5ff0ac371d0457fbab9;hpb=135b5dee0e7ed1e8cb9929fe78e72b9fa0fa7ece;p=webserver.git diff --git a/file.c b/file.c index 4a866b6..786a895 100644 --- a/file.c +++ b/file.c @@ -1,11 +1,14 @@ #include #include #include +#include #include "debug.h" #include "file.h" +#define TLEN 8 + /* read full file */ int readfile (char **buffer, char *filename) @@ -13,24 +16,76 @@ int readfile (char **buffer, char *filename) /* open file */ + VERBOSE (DEBUG, PRINT ("Opening file %s for reading\n", filename)); FILE *fd = fopen (filename, "rb"); if (fd == NULL) { - VERBOSE (WARNING, PRINT ("Can't open file (%s)\n", filename)); + VERBOSE (WARNING, PRINT ("Can't open file (%s) for reading\n", filename)); return -1; } + VERBOSE (DEBUG, PRINT ("Seek file size\n")); fseek (fd, 0, SEEK_END); int size = ftell (fd); fseek (fd, 0, SEEK_SET); /* same as rewind(f); */ /* read full file */ + VERBOSE (DEBUG, PRINT ("Reading %d bytes\n", size)); *buffer = calloc (size + 1, 1); - fread (*buffer, size, 1, fd); + int len = fread (*buffer, 1, size, fd); + if (len != size) { + VERBOSE (WARNING, PRINT ("Can't read full file (%s)\n", filename)); + } + fclose (fd); + + (*buffer)[len] = 0; + return len; +} + +/* temp name */ + +char *tempname (char *tempdir, char *ext) +{ + char table[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"; + + unsigned int len = strlen (tempdir) + 1 + 4 + TLEN + ((ext) ? strlen (ext) : 0) + 1; + char *name = (char *) calloc (len, 1); + + sprintf (name, "%s/tmp-", tempdir); + while (strlen (name) + 1 < len - ((ext) ? strlen (ext) : 0)) { + name[strlen (name)] = table[rand () % 64]; + } + if (ext) { + strcat (name, ext); + } + + return name; +} + +/* write full file */ + +int writefile (char *filename, char *buffer, int size) +{ + + /* open file */ + + VERBOSE (DEBUG, PRINT ("Opening file %s for writing\n", filename)); + FILE *fd = fopen (filename, "wb"); + if (fd == NULL) { + VERBOSE (WARNING, PRINT ("Can't open file (%s) for writing\n", filename)); + return -1; + } + + /* write full file */ + + VERBOSE (DEBUG, PRINT ("Writing %d bytes\n", size)); + int len = fwrite (buffer, size, 1, fd); + if (len != size) { + VERBOSE (WARNING, PRINT ("Can't write full file (%s)\n", filename)); + } fclose (fd); - *buffer[size] = 0; - return size; + return len; } /* vim: set ts=4 sw=4 et: */