file_contents_as_string.h 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #ifndef IGL_FILE_CONTENTS_AS_STRING_H
  2. #define IGL_FILE_CONTENTS_AS_STRING_H
  3. #include <string>
  4. namespace igl
  5. {
  6. // Read a files contents as plain text into a given string
  7. // Inputs:
  8. // file_name path to file to be read
  9. // Outputs:
  10. // content output string containing contents of the given file
  11. // Returns true on succes, false on error
  12. inline bool file_contents_as_string(
  13. const std::string file_name,
  14. std::string & content);
  15. }
  16. // Implementation
  17. #include <fstream>
  18. #include <cstdio>
  19. inline bool igl::file_contents_as_string(
  20. const std::string file_name,
  21. std::string & content)
  22. {
  23. std::ifstream ifs(file_name.c_str());
  24. // Check that opening the stream worked successfully
  25. if(!ifs.good())
  26. {
  27. fprintf(
  28. stderr,
  29. "IOError: file_contents_as_string() cannot open %s\n",
  30. file_name.c_str());
  31. return false;
  32. }
  33. // Stream file contents into string
  34. content = std::string(
  35. (std::istreambuf_iterator<char>(ifs)),
  36. (std::istreambuf_iterator<char>()));
  37. return true;
  38. }
  39. #endif