test.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. libnbt++ - A library for the Minecraft Named Binary Tag format.
  3. Copyright (C) 2013 ljfa-ag
  4. This file is part of libnbt++.
  5. libnbt++ is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. libnbt++ is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with libnbt++. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #include "tag.h"
  17. #include "nbt_io.h"
  18. #include <fstream>
  19. #include <iostream>
  20. #include <cstring>
  21. int main(int argc, const char* const* argv)
  22. {
  23. if(argc < 2)
  24. {
  25. std::cerr << "Usage: nbttest input [output]" << std::endl;
  26. return 1;
  27. }
  28. const char* filename = argv[1];
  29. std::ifstream file(filename, std::ios::binary);
  30. if(!file)
  31. {
  32. std::cerr << "Error opening file \"" << filename << "\"." << std::endl;
  33. return 2;
  34. }
  35. int magic_num = file.peek();
  36. bool uncompressed;
  37. if(magic_num == 0x1F) //First byte of a gzip file
  38. uncompressed = false;
  39. else if(magic_num == 0x0A) //First byte of an uncompressed NBT file
  40. uncompressed = true;
  41. else
  42. {
  43. std::cerr << "Invalid file format of \"" << filename << "\"." << std::endl;
  44. return 2;
  45. }
  46. std::string key;
  47. std::unique_ptr<nbt::tag> tp;
  48. try
  49. {
  50. if(uncompressed)
  51. tp = nbt::io::read(file, key);
  52. else
  53. tp = nbt::io::read_gzip(file, key);
  54. }
  55. catch(std::exception& ex)
  56. {
  57. std::cerr << "Error reading file \"" << filename << "\": " << ex.what() << std::endl;
  58. return 3;
  59. }
  60. file.close();
  61. std::cout << "Contents of ";
  62. if(uncompressed)
  63. std::cout << "uncompressed ";
  64. std::cout << "NBT file \"" << filename << "\":\n\n\"" << key << "\" -> " << *tp << std::endl;
  65. if(argc < 3)
  66. return 0;
  67. const char* output = argv[2];
  68. std::ofstream outf(output, std::ios::binary);
  69. nbt::io::write_gzip(outf, key, *tp);
  70. std::cout << "\nOutput written to \"" << output << "\"." << std::endl;
  71. return 0;
  72. }