#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 (unsigned char **buffer, char *filename)
+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: */