]> SALOME platform Git repositories - tools/libbatch.git/blobdiff - src/Core/Batch_Utils.cxx
Salome HOME
Merge class BatchManager_eClient into class BatchManager
[tools/libbatch.git] / src / Core / Batch_Utils.cxx
index e3c864a49078e1af1dc1e434564ba74e6bd3096c..5d173bcbbf59d341190ca2c5e0defaa93474aacc 100644 (file)
  *  Author : Renaud BARATE - EDF R&D
  */
 
+#include <cstdlib>
 #include <cstdio>
+#include <unistd.h>
+#include <iostream>
+#include <fstream>
 
 #include <Batch_config.h>
 #include "Batch_Utils.hxx"
+#include "Batch_RunTimeException.hxx"
 
 #ifdef MSVC
 #define popen _popen
@@ -68,4 +73,56 @@ bool Utils::isAbsolutePath(const string & path)
   return path[0] == '/';
 }
 
+string Utils::createAndOpenTemporaryFile(const string & prefix, ofstream & outputStream)
+{
+  if (outputStream.is_open())
+    outputStream.close();
+
+  // Find directory for temporary files
+  const char * tmpDirName = getenv("TEMP");
+  if (tmpDirName == NULL) tmpDirName = getenv("TMP");
+  if (tmpDirName == NULL) tmpDirName = getenv("TEMPDIR");
+  if (tmpDirName == NULL) tmpDirName = getenv("TMPDIR");
+  if (tmpDirName == NULL) tmpDirName = "/tmp";
+
+  string fileName = (string)tmpDirName + "/libbatch-" + prefix + "-XXXXXX";
+
+#ifdef WIN32
+
+  char randstr[7];
+  srand(time(NULL));
+
+  do {
+    sprintf(randstr, "%06d", rand() % 1000000);
+    fileName.replace(fileName.size()-6, 6, randstr);
+  } while (EXISTS(fileName.c_str()));
+
+  // Open the file as binary to avoid problems with Windows newlines
+  outputStream.open(fileName.c_str(), ios_base::binary | ios_base::out);
+
+#else
+
+  char * buf = new char[fileName.size()+1];
+  fileName.copy(buf, fileName.size());
+  buf[fileName.size()] = '\0';
+
+  int fd = mkstemp(buf);
+  if (fd == -1) {
+    delete[] buf;
+    throw RunTimeException(string("Can't create temporary file ") + fileName);
+  }
+  fileName = buf;
+  delete[] buf;
+
+  outputStream.open(fileName.c_str());
+  close(fd);  // Close the file descriptor so that the file is not opened twice
+
+#endif
+
+  if (outputStream.fail())
+    throw RunTimeException(string("Can't open temporary file ") + fileName);
+
+  return fileName;
+}
+
 }