Przeglądaj źródła

* First class!!: Tempfile

svn: 1322
Bryan Drewery 22 lat temu
rodzic
commit
aea88c2d5c
2 zmienionych plików z 53 dodań i 0 usunięć
  1. 37 0
      src/misc_file.c
  2. 16 0
      src/misc_file.h

+ 37 - 0
src/misc_file.c

@@ -10,6 +10,8 @@
 #include <fcntl.h>
 #include <errno.h>
 #include "stat.h"
+#include "misc_file.h"
+#include "main.h"
 
 
 /* Copy a file from one place to another (possibly erasing old copy).
@@ -145,3 +147,38 @@ int fixmod(const char *s)
   return 0;
 #endif /* !CYGWIN_HACKS */
 }
+
+Tempfile::Tempfile()
+{
+  file = new char[strlen(tempdir) + 7 + 1];
+  sprintf(file, "%s.XXXXXX", tempdir);
+
+  MakeTemp();
+}
+
+Tempfile::Tempfile(const char *prefix)
+{
+  file = new char[strlen(tempdir) + strlen(prefix) + 7 + 1];
+  sprintf(file, "%s.%s-XXXXXX", tempdir, prefix);
+
+  MakeTemp();
+}
+
+void Tempfile::MakeTemp()
+{
+  if ((fd = mkstemp(file)) == -1 || (f = fdopen(fd, "wb")) == NULL) {
+    if (fd != -1) {
+      unlink(file);
+      close(fd);
+    }
+    fatal("Cannot create temporary file!", 0);
+  }
+}
+
+Tempfile::~Tempfile()
+{
+  close(fd);
+  unlink(file);
+  delete[] file;
+}
+

+ 16 - 0
src/misc_file.h

@@ -7,6 +7,8 @@
 #ifndef _EGG_MISC_FILE_H
 #define _EGG_MISC_FILE_H
 
+#include <stdio.h>
+
 int copyfile(const char *, const char *);
 int movefile(const char *, const char *);
 int is_file(const char *);
@@ -16,4 +18,18 @@ int is_symlink(const char *);
 int is_dir(const char *);
 int fixmod(const char *);
 
+class Tempfile 
+{
+  public:
+    Tempfile();					//constructor
+    Tempfile(const char *prefix);		//constructor with file prefix
+    ~Tempfile();				//destructor
+
+    FILE *f;
+    int fd;
+    char *file;
+  private:
+    void MakeTemp();				//Used for mktemp() and checking
+};
+
 #endif				/* _EGG_MISC_FILE_H */