Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdlib>
- #include <fstream>
- #include <string>
- #include <array>
- template<typename T>
- std::ostream& writeblock(std::ostream& out, const T& block){
- return out.write(
- reinterpret_cast<const char*>(&block),
- sizeof block
- );
- }
- template<typename T>
- std::istream& readblock(std::istream& in, T& block){
- return in.read(
- reinterpret_cast<char*>(&block),
- sizeof block
- );
- }
- template<typename T>
- std::string packstring(T& a, const std::string& s)
- {
- if (s.length() >= a.size()) // no entra
- a.at(a.size()-1) = '\0'; // pone un 0 en el ultimo
- else
- a.at(s.length()) = '\0'; // pone un 0 despues del string
- s.copy(a.data(), a.size()-1); // donde copiar, cuanto copiar
- return s;
- }
- template<typename T>
- std::string unpackstring(const T& a){
- return std::string(a.data(), a.size());
- }
- template<typename stream_type>
- void check_open (const stream_type& file)
- {
- if (not file.is_open())
- {
- std::cout << "Archivo no abierto." << std::endl;
- std::exit(1);
- }
- }
- template<typename stream_type>
- void close_file (stream_type& file)
- {
- file.close();
- }
- struct record {
- char numero;
- char letra;
- };
- using namespace std;
- int main()
- {
- array<char,10> a;
- record rec = {'A', 'B'};
- string s = "Hello world!";
- packstring(a, s);
- s = unpackstring(a);
- cout << s << endl;
- ofstream out("filename.bin", ios::binary);
- writeblock(out, rec);
- out.close();
- ifstream in("filename.bin", ios::binary);
- readblock(in, rec);
- close_file(in);
- cout << rec.letra << ' ' << rec.numero << endl;
- //cout << rec[0] << rec[1] << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement