OSDN Git Service

7e6ec6c9bc29eb8b3bda38b88f1d5b255fadec78
[meshio/meshio.git] / src / binary.cpp
1 #include "binary.h"
2
3 namespace meshio {
4 namespace binary {
5
6 ///////////////////////////////////////////////////////////////////////////////
7 // FileReader
8 ///////////////////////////////////////////////////////////////////////////////
9 FileReader::FileReader(const char *path)
10 : io_(path, std::ios::binary), pos_(0), eof_(false)
11 {
12 }
13
14 FileReader::~FileReader()
15 {
16 }
17
18 unsigned int FileReader::read(char *buf, unsigned int size)
19 {
20         if(size==0){
21                 return 0;
22         }
23         io_.read(buf, size);
24         size=io_.gcount();
25         if(size==0){
26                 eof_=true;
27         }
28         pos_+=size;
29         return size;
30 }
31
32 unsigned int FileReader::getPos()const
33 {
34         return pos_;
35 }
36
37 bool FileReader::isEnd()const
38 {
39         return eof_;
40 }
41
42 ///////////////////////////////////////////////////////////////////////////////
43 // MemoryReader
44 ///////////////////////////////////////////////////////////////////////////////
45 MemoryReader::MemoryReader(const char *buf, unsigned int size)
46 : buf_(buf), size_(size), pos_(0)
47 {
48 }
49
50 MemoryReader::~MemoryReader()
51 {
52 }
53
54 unsigned int MemoryReader::read(char *buf, unsigned int size)
55 {
56         if(pos_+size>=size_){
57                 size=size_-pos_;
58         }
59         std::copy(&buf_[pos_], &buf_[pos_+size], buf);
60         pos_+=size;
61         return size;
62 }
63
64 unsigned int MemoryReader::getPos()const
65 {
66         return pos_;
67 }
68
69 bool MemoryReader::isEnd()const
70 {
71         return pos_>=size_;
72 }
73
74 ///////////////////////////////////////////////////////////////////////////////
75 void readAll(const char *path, std::vector<char> &buf)
76 {
77         std::ifstream io(path, std::ios::binary);
78         if(!io){
79                 return;
80         }
81         io.seekg(0, std::fstream::end);
82         unsigned int eofPos = io.tellg();
83         io.clear();
84         io.seekg(0, std::fstream::beg);
85         unsigned int begPos = io.tellg();
86         unsigned int size = eofPos - begPos;
87         buf.resize(size);
88         io.read(&buf[0], buf.size());
89 }
90
91 } // namespace binary
92 } // namespace meshio