OSDN Git Service

52a8a337b1c41c16053457e31f5ed34b2f49ba0f
[meshio/meshio.git] / src / binary.cpp
1 #include "binary.h"
2
3 namespace meshio {
4   namespace binary {
5
6     // FileReader
7     FileReader::FileReader(const char *path)
8       : io_(path, std::ios::binary), pos_(0), eof_(false)
9     {
10     }
11
12     FileReader::~FileReader()
13     {
14     }
15
16     unsigned int FileReader::read(char *buf, unsigned int size)
17     {
18       if(size==0){
19         return 0;
20       }
21       io_.read(buf, size);
22       size_t read_size=static_cast<size_t>(io_.gcount());
23       if(read_size==0){
24         eof_=true;
25       }
26       pos_+=read_size;
27       return read_size;
28     }
29
30     unsigned int FileReader::getPos()const
31     {
32       return pos_;
33     }
34
35     bool FileReader::isEnd()const
36     {
37       return eof_;
38     }
39
40     // MemoryReader
41     MemoryReader::MemoryReader(const char *buf, unsigned int size)
42       : buf_(buf), size_(size), pos_(0)
43     {
44     }
45
46     MemoryReader::~MemoryReader()
47     {
48     }
49
50     unsigned int MemoryReader::read(char *buf, unsigned int size)
51     {
52       if(pos_+size>=size_){
53         size=size_-pos_;
54       }
55       std::copy(&buf_[pos_], &buf_[pos_+size], buf);
56       pos_+=size;
57       return size;
58     }
59
60     unsigned int MemoryReader::getPos()const
61     {
62       return pos_;
63     }
64
65     bool MemoryReader::isEnd()const
66     {
67       return pos_>=size_;
68     }
69
70     // readALL
71     static void readALL_(FILE *fp, std::vector<char> &buf)
72     {
73       int iRet = fseek(fp, 0L, SEEK_END);
74       if(iRet!=0){
75         return;
76       }
77
78       long pos=ftell(fp);
79       if(pos == -1){
80         return;
81       }
82
83       iRet = fseek(fp, 0L, SEEK_SET);
84       if(iRet != 0){
85         return;
86       }
87
88       buf.resize(pos);
89       iRet=fread(&buf[0], pos, 1, fp);
90     }
91
92     void readAll(const char *path, std::vector<char> &buf)
93     {
94       FILE* fp = fopen(path, "rb");
95       if(fp){
96         readALL_(fp, buf);
97         fclose(fp);
98       }
99     }
100
101 #ifdef _WIN32
102     void readAll(const wchar_t *path, std::vector<char> &buf)
103     {
104       FILE* fp = _wfopen(path, L"rb");
105       if(fp){
106         readALL_(fp, buf);
107         fclose(fp);
108       }
109     }
110 #endif
111
112     // FileWriter
113     FileWriter::FileWriter(const char *path)
114     {
115       io_=fopen(path, "wb");
116     }
117
118 #if _WIN32
119     FileWriter::FileWriter(const wchar_t *path)
120     {
121       io_=_wfopen(path, L"wb");
122     }
123 #endif
124
125     FileWriter::~FileWriter()
126     {
127       fclose(io_);
128     }
129
130     void FileWriter::write(const char *buf, unsigned int size)
131     {
132       fwrite(buf, size, 1, io_);
133     }
134
135
136   } // namespace binary
137 } // namespace meshio