My Project
FileUtil.h
Go to the documentation of this file.
1 #ifndef _FILEUTIL_H__
2 #define _FILEUTIL_H__
3 
4 #include <fstream>
5 #include <iostream>
6 #include <string.h>
7 #include <unistd.h>
8 #include <string>
9 
17 class FileUtil
18 {
19 public:
20 
28  static std::string createTempFilename(const std::string& prefix, const std::string& suffix = "") {
29  char fname[1000];
30  strcat(strcpy(fname, prefix.c_str()), ".XXXXXX");
31  if (not suffix.empty()) strcat(fname, suffix.c_str());
32  int file = mkstemps(fname, suffix.size());
33  if (file == -1) return "";
34  return fname;
35  }
36 
41  static void deleteTempFilename(const std::string& filename) {
42  unlink(filename.c_str());
43  }
44 
53  static bool write(const std::string& s, const std::string& filename, std::string& error) {
54  if (filename.empty()) {
55  std::cout << s;
56  return true;
57  }
58 
59  std::ofstream f(filename);
60  if (not f.good()) {
61  error = "Error when opening the output file " + filename + ".";
62  return false;
63  }
64 
65  f << s;
66  f.close();
67  return true;
68  }
69 };
70 
71 #endif // _FILEUTIL_H__
static std::string createTempFilename(const std::string &prefix, const std::string &suffix="")
Creates a temporary file name with the format "prefix".XXXXXXsuffix. This format is used with mkstemp...
Definition: FileUtil.h:28
static bool write(const std::string &s, const std::string &filename, std::string &error)
Writes a string into a file.
Definition: FileUtil.h:53
static void deleteTempFilename(const std::string &filename)
Deletes a temporary file name.
Definition: FileUtil.h:41
Definition: FileUtil.h:17