* 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
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;
+}
+
}