best makefile
[webserver.git] / file.c
diff --git a/file.c b/file.c
index 47f91a7c8b21b647844bd8a378bfbcb271e103c7..786a895c1b8d9c6b896c3aa921b908079f8847d9 100644 (file)
--- a/file.c
+++ b/file.c
@@ -1,11 +1,14 @@
 #include <malloc.h>
 #include <stdio.h>
 #include <stdlib.h>
+#include <string.h>
 
 #include "debug.h"
 
 #include "file.h"
 
+#define TLEN 8
+
 /* read full file */
 
 int readfile (char **buffer, char *filename)
@@ -13,10 +16,10 @@ int readfile (char **buffer, char *filename)
 
     /* open file */
 
-    VERBOSE (DEBUG, PRINT ("Opening file %s\n", filename));
+    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;
     }
 
@@ -29,11 +32,60 @@ int readfile (char **buffer, char *filename)
 
     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: */