stdin_to_temp.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #ifndef IGL_STDIN_TO_TEMP
  2. #define IGL_STDIN_TO_TEMP
  3. #include <cstdio>
  4. namespace igl
  5. {
  6. // Write stdin/piped input to a temporary file which can than be preprocessed as it
  7. // is (a normal file). This is often useful if you want to process stdin/piped
  8. // with library functions that expect to be able to fseek(), rewind() etc..
  9. //
  10. // If your application is not using fseek(), rewind(), etc. but just reading
  11. // from stdin then this will likely cause a bottle neck as it defeats the whole
  12. // purpose of piping.
  13. //
  14. // Outputs:
  15. // temp_file pointer to temp file pointer, rewound to beginning of file so
  16. // its ready to be read
  17. // Return true only if no errors were found
  18. //
  19. // Note: Caller is responsible for closing the file (tmpfile() automatically
  20. // unlinks the file so there is no need to remove/delete/unlink the file)
  21. inline bool stdin_to_temp(FILE ** temp_file);
  22. }
  23. // IMPLEMENTATION
  24. #include <iostream>
  25. inline bool igl::stdin_to_temp(FILE ** temp_file)
  26. {
  27. // get a temporary file
  28. *temp_file = tmpfile();
  29. if(*temp_file == NULL)
  30. {
  31. fprintf(stderr,"IOError: temp file could not be created.\n");
  32. return false;
  33. }
  34. char c;
  35. // c++'s cin handles the stdind input in a reasonable way
  36. while (std::cin.good())
  37. {
  38. c = std::cin.get();
  39. if(std::cin.good())
  40. {
  41. if(1 != fwrite(&c,sizeof(char),1,*temp_file))
  42. {
  43. fprintf(stderr,"IOError: error writing to tempfile.\n");
  44. return false;
  45. }
  46. }
  47. }
  48. // rewind file getting it ready to read from
  49. rewind(*temp_file);
  50. return true;
  51. }
  52. #endif