Advertisement
rihardmarius

uso de libreria archivos

Nov 24th, 2013
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <fstream>
  4. #include <string>
  5. #include <array>
  6.  
  7. template<typename T>
  8. std::ostream& writeblock(std::ostream& out, const T& block){
  9.     return out.write(
  10.         reinterpret_cast<const char*>(&block),
  11.         sizeof block
  12.     );
  13. }
  14.  
  15.  
  16. template<typename T>
  17. std::istream& readblock(std::istream& in, T& block){
  18.     return in.read(
  19.         reinterpret_cast<char*>(&block),
  20.         sizeof block
  21.     );
  22. }
  23.  
  24. template<typename T>
  25. std::string packstring(T& a, const std::string& s)
  26. {
  27.     if (s.length() >= a.size()) // no entra
  28.         a.at(a.size()-1) = '\0'; // pone un 0 en el ultimo
  29.     else
  30.         a.at(s.length()) = '\0'; // pone un 0 despues del string
  31.     s.copy(a.data(), a.size()-1); // donde copiar, cuanto copiar
  32.     return s;
  33. }
  34.  
  35. template<typename T>
  36. std::string unpackstring(const T& a){
  37.     return std::string(a.data(), a.size());
  38. }
  39.  
  40. template<typename stream_type>
  41. void check_open (const stream_type& file)
  42. {
  43.     if (not file.is_open())
  44.     {
  45.         std::cout << "Archivo no abierto." << std::endl;
  46.         std::exit(1);
  47.     }
  48. }
  49.  
  50. template<typename stream_type>
  51. void close_file (stream_type& file)
  52. {
  53.     file.close();
  54. }
  55.  
  56. struct record {
  57.     char numero;
  58.     char letra;
  59. };
  60.  
  61. using namespace std;
  62.  
  63. int main()
  64. {
  65.     array<char,10> a;
  66.     record rec = {'A', 'B'};
  67.  
  68.     string s = "Hello world!";
  69.     packstring(a, s);
  70.     s = unpackstring(a);
  71.  
  72.     cout << s << endl;
  73.  
  74.     ofstream out("filename.bin", ios::binary);
  75.     writeblock(out, rec);
  76.     out.close();
  77.  
  78.     ifstream in("filename.bin", ios::binary);
  79.     readblock(in, rec);
  80.     close_file(in);
  81.  
  82.     cout << rec.letra << ' ' << rec.numero << endl;
  83.     //cout << rec[0] << rec[1] << endl;
  84.  
  85.     return 0;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement