code_junkie

How to create a std::ofstream to a temp file

Nov 14th, 2011
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. warning: the use of `tmpnam' is dangerous, better use `mkstemp'
  2.  
  3. char *tmpname = strdup("/tmp/tmpfileXXXXXX");
  4. ofstream f;
  5. int fd = mkstemp(tmpname);
  6. f.attach(fd);
  7.  
  8. char *tmpname = strdup("/tmp/tmpfileXXXXXX");
  9. mkstemp(tmpname);
  10. ofstream f(tmpname);
  11.  
  12. #include <stdlib.h>
  13. #include <fstream>
  14. #include <iostream>
  15. #include <vector>
  16.  
  17. std::string open_temp(std::string path, std::ofstream& f) {
  18. path += "/XXXXXX";
  19. std::vector<char> dst_path(path.begin(), path.end());
  20. dst_path.push_back('');
  21.  
  22. int fd = mkstemp(&dst_path[0]);
  23. if(fd != -1) {
  24. path.assign(dst_path.begin(), dst_path.end() - 1);
  25. f.open(path.c_str(),
  26. std::ios_base::trunc | std::ios_base::out);
  27. close(fd);
  28. }
  29. return path;
  30. }
  31.  
  32. int main() {
  33. std::ofstream logfile;
  34. open_temp("/tmp", logfile);
  35. if(logfile.is_open()) {
  36. logfile << "hello, dude" << std::endl;
  37. }
  38. }
  39.  
  40. char tmpname[256];
  41. ofstream f;
  42. sprintf (tmpname, "/tmp/tmpfileXXXX");
  43. int fd = mkstemp(tmpname);
  44. ofstream f(tmpname);
Add Comment
Please, Sign In to add comment