file_write_read.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // https://cirosantilli.com/linux-kernel-module-cheat#cpp
  2. #include <lkmc.h>
  3. #include <cassert>
  4. #include <fstream>
  5. #include <sstream>
  6. // https://stackoverflow.com/questions/116038/what-is-the-best-way-to-read-an-entire-file-into-a-stdstring-in-c
  7. // https://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring
  8. std::string read_file(const std::string& path) {
  9. std::ifstream ifs(path);
  10. assert(ifs.is_open());
  11. std::stringstream sstr;
  12. sstr << ifs.rdbuf();
  13. return sstr.str();
  14. }
  15. int main(void) {
  16. std::string path = LKMC_TMP_FILE;
  17. std::string data = "asdf\nqwer\n";
  18. // Write entire string to file at once.
  19. {
  20. std::ofstream ofs(path);
  21. assert(ofs.is_open());
  22. ofs << data;
  23. ofs.close();
  24. }
  25. // Read entire file into string.
  26. std::string read_output = read_file(path);
  27. assert(read_output == data);
  28. // Append to a file.
  29. {
  30. std::string append_data = "zxcv\n";
  31. std::ofstream ofs(path, std::ios::app);
  32. assert(ofs.is_open());
  33. ofs << append_data;
  34. ofs.close();
  35. assert(read_file(path) == data + append_data);
  36. }
  37. return EXIT_SUCCESS;
  38. }