{"id":17246,"date":"2024-03-26T20:51:15","date_gmt":"2024-03-26T20:51:15","guid":{"rendered":"http:\/\/www.max-sperling.bplaced.net\/?p=17246"},"modified":"2024-03-26T21:21:36","modified_gmt":"2024-03-26T21:21:36","slug":"read-write-binary-file-c","status":"publish","type":"post","link":"http:\/\/www.max-sperling.bplaced.net\/?p=17246","title":{"rendered":"Read\/Write binary files (C++)"},"content":{"rendered":"<pre class=\"brush: cpp; gutter: false; title: main.cpp; notranslate\" title=\"main.cpp\">\r\n#include &lt;cassert&gt;\r\n#include &lt;cstdint&gt;\r\n#include &lt;fstream&gt;\r\n#include &lt;iostream&gt;\r\n#include &lt;vector&gt;\r\n\r\nstruct Book\r\n{\r\n    Book() : m_title(&quot;&quot;), m_author(&quot;&quot;), m_pages(0) { }\r\n\r\n    Book(const std::string&amp; title, const std::string&amp; author, uint16_t pages)\r\n    : m_title(title), m_author(author), m_pages(pages) { }\r\n\r\n    friend bool operator==(const Book&amp; b1, const Book&amp; b2)\r\n    {\r\n        return b1.m_title == b2.m_title &amp;&amp;\r\n               b1.m_author == b2.m_author &amp;&amp;\r\n               b1.m_pages == b2.m_pages;\r\n    }\r\n\r\n    void print()\r\n    {\r\n        std::cout &lt;&lt; &quot;Title: &quot; &lt;&lt; m_title &lt;&lt; &quot;, &quot;\r\n                  &lt;&lt; &quot;Author: &quot; &lt;&lt; m_author &lt;&lt; &quot;, &quot;\r\n                  &lt;&lt; &quot;Pages: &quot; &lt;&lt; m_pages &lt;&lt; std::endl;\r\n    }\r\n\r\n    std::string m_title;\r\n    std::string m_author;\r\n    uint16_t m_pages;\r\n};\r\n\r\nclass Library\r\n{\r\npublic:\r\n    Library() : m_fileName(&quot;data.bin&quot;) { }\r\n\r\n    void add(const Book&amp; book)\r\n    {\r\n        m_books.push_back(book);\r\n    }\r\n\r\n    size_t size()\r\n    {\r\n        return m_books.size();\r\n    }\r\n\r\n    Book&amp; at(size_t pos)\r\n    {\r\n        return m_books.at(pos);\r\n    }\r\n\r\n    void print()\r\n    {\r\n        for (auto&amp; book : m_books)\r\n        {\r\n            book.print();\r\n        }\r\n    }\r\n\r\n    void writeToFile()\r\n    {\r\n        std::fstream fs(m_fileName, std::ios::out | std::ios::binary);\r\n        if (!fs.is_open())\r\n        {\r\n            std::cout &lt;&lt; &quot;Error opening file for writing&quot; &lt;&lt; std::endl;\r\n            return;\r\n        }\r\n\r\n        for (const auto&amp; book : m_books)\r\n        {\r\n            \/\/ Write title\r\n            uint16_t titleLen = book.m_title.size();\r\n            fs.write(reinterpret_cast&lt;const char*&gt;(&amp;titleLen),\r\n                     sizeof(titleLen));\r\n            fs.write(book.m_title.c_str(), titleLen); \/\/ w\/o &#039;&#92;&#48;&#039;\r\n\r\n            \/\/ Write author\r\n            uint16_t authorLen = book.m_author.size();\r\n            fs.write(reinterpret_cast&lt;const char*&gt;(&amp;authorLen),\r\n                     sizeof(authorLen));\r\n            fs.write(book.m_author.c_str(), authorLen); \/\/ w\/o &#039;&#92;&#48;&#039;\r\n\r\n            \/\/ Write pages\r\n            fs.write(reinterpret_cast&lt;const char*&gt;(&amp;book.m_pages),\r\n                     sizeof(book.m_pages));\r\n        }\r\n\r\n        fs.close();\r\n    }\r\n\r\n    void readFromFile()\r\n    {\r\n        std::fstream fs(m_fileName, std::ios::in | std::ios::binary);\r\n        if (!fs.is_open())\r\n        {\r\n            std::cout &lt;&lt; &quot;Error opening file for reading&quot; &lt;&lt; std::endl;\r\n            return;\r\n        }\r\n\r\n        while (!fs.eof())\r\n        {\r\n            Book book;\r\n\r\n            \/\/ Read title\r\n            uint16_t titleLen;\r\n            fs.read(reinterpret_cast&lt;char*&gt;(&amp;titleLen),\r\n                    sizeof(titleLen));\r\n            book.m_title.resize(titleLen);\r\n            fs.read(&amp;book.m_title[0], titleLen);\r\n\r\n            \/\/ Read author\r\n            uint16_t authorLen;\r\n            fs.read(reinterpret_cast&lt;char*&gt;(&amp;authorLen),\r\n                    sizeof(authorLen));\r\n            book.m_author.resize(authorLen);\r\n            fs.read(&amp;book.m_author[0], authorLen);\r\n\r\n            \/\/ Read pages\r\n            fs.read(reinterpret_cast&lt;char*&gt;(&amp;book.m_pages),\r\n                    sizeof(book.m_pages));\r\n\r\n            m_books.push_back(book);\r\n\r\n            fs.peek();\r\n        }\r\n\r\n        fs.close();\r\n    }\r\n\r\nprivate:\r\n    std::vector&lt;Book&gt; m_books;\r\n    const char* m_fileName;\r\n};\r\n\r\nint main()\r\n{\r\n    Library lib1;\r\n    lib1.add(Book(&quot;The Hound of the Baskervilles&quot;, &quot;A.C. Doyle&quot;, 224));\r\n    lib1.add(Book(&quot;The Fellowship of the Ring&quot;, &quot;J.R.R. Tolkien&quot;, 576));\r\n    lib1.writeToFile();\r\n\r\n    Library lib2;\r\n    lib2.readFromFile();\r\n\r\n    assert(lib1.size() == lib2.size());\r\n\r\n    for(size_t i = 0; i &lt; lib1.size(); ++i)\r\n    {\r\n        assert(lib1.at(i) == lib2.at(i));\r\n    }\r\n    \r\n    std::cout &lt;&lt; &quot;All tests successful&quot; &lt;&lt; std::endl;\r\n\r\n    return 0;\r\n}\r\n<\/pre>\n<hr>\n<pre class=\"brush: plain; gutter: false; title: data.bin; notranslate\" title=\"data.bin\">\r\n00   1d00 5468 6520 486f 756e 6420 6f66 2074   __The Hound of t\r\n10   6865 2042 6173 6b65 7276 696c 6c65 730a   he Baskervilles_\r\n20   0041 2e43 2e20 446f 796c 65e0 001a 0054   _A.C. Doyle____T\r\n30   6865 2046 656c 6c6f 7773 6869 7020 6f66   he Fellowship of\r\n40   2074 6865 2052 696e 670e 004a 2e52 2e52    the Ring__J.R.R\r\n50   2e20 546f 6c6b 6965 6e40 02               . Tolkien__\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false},"categories":[27],"tags":[],"_links":{"self":[{"href":"http:\/\/www.max-sperling.bplaced.net\/index.php?rest_route=\/wp\/v2\/posts\/17246"}],"collection":[{"href":"http:\/\/www.max-sperling.bplaced.net\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.max-sperling.bplaced.net\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.max-sperling.bplaced.net\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/www.max-sperling.bplaced.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=17246"}],"version-history":[{"count":11,"href":"http:\/\/www.max-sperling.bplaced.net\/index.php?rest_route=\/wp\/v2\/posts\/17246\/revisions"}],"predecessor-version":[{"id":17255,"href":"http:\/\/www.max-sperling.bplaced.net\/index.php?rest_route=\/wp\/v2\/posts\/17246\/revisions\/17255"}],"wp:attachment":[{"href":"http:\/\/www.max-sperling.bplaced.net\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=17246"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.max-sperling.bplaced.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=17246"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.max-sperling.bplaced.net\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=17246"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}