TestUtil.cc 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #include "TestUtil.h"
  2. #include <sys/types.h>
  3. #include <sys/stat.h>
  4. #include <fcntl.h>
  5. #include <cerrno>
  6. #include <cstring>
  7. #include <sstream>
  8. #include <fstream>
  9. #include "a2io.h"
  10. #include "File.h"
  11. #include "StringFormat.h"
  12. #include "FatalException.h"
  13. namespace aria2 {
  14. void createFile(const std::string& path, size_t length)
  15. {
  16. File(File(path).getDirname()).mkdirs();
  17. int fd = creat(path.c_str(), OPEN_MODE);
  18. if(fd == -1) {
  19. throw FATAL_EXCEPTION(StringFormat("Could not create file=%s. cause:%s",
  20. path.c_str(), strerror(errno)).str());
  21. }
  22. if(-1 == ftruncate(fd, length)) {
  23. throw FATAL_EXCEPTION(StringFormat("ftruncate failed. cause:%s",
  24. strerror(errno)).str());
  25. }
  26. close(fd);
  27. }
  28. std::string readFile(const std::string& path)
  29. {
  30. std::stringstream ss;
  31. std::ifstream in(path.c_str(), std::ios::binary);
  32. char buf[4096];
  33. while(1) {
  34. in.read(buf, sizeof(buf));
  35. ss.write(buf, in.gcount());
  36. if(in.gcount() != sizeof(buf)) {
  37. break;
  38. }
  39. }
  40. return ss.str();
  41. }
  42. };