Worldstone
 All Classes Files Functions Variables Enumerations Enumerator Macros Pages
FileStream.cpp
1 //
2 // Created by Lectem on 12/11/2016.
3 //
4 
5 #include "FileStream.h"
6 #include <assert.h>
7 
8 namespace WorldStone
9 {
10 
11 FileStream::FileStream(const Path& filename) { open(filename); }
12 
13 FileStream::~FileStream() { close(); }
14 
15 bool FileStream::open(const Path& filename)
16 {
17  file = fopen(filename.c_str(), "rb");
18  if (!file) setstate(failbit);
19  return good();
20 }
21 
22 bool FileStream::close()
23 {
24  if (!file || fclose(file)) setstate(failbit);
25  file = nullptr;
26  return good();
27 }
28 
29 size_t FileStream::read(void* buffer, size_t size)
30 {
31  assert(is_open());
32  const size_t readSize = fread(buffer, sizeof(char), size, file);
33  if (readSize != size) {
34  if (feof(file)) {
35  setstate(eofbit);
36  }
37  setstate(failbit);
38  }
39  return readSize;
40 }
41 
43 {
44  assert(is_open());
45  return ftell(file);
46 }
47 
48 // We assume there's no need for conversion, which is probably wrong on some platforms
49 static_assert(FileStream::beg == SEEK_SET, "");
50 static_assert(FileStream::cur == SEEK_CUR, "");
51 static_assert(FileStream::end == SEEK_END, "");
52 bool FileStream::seek(long offset, IStream::seekdir origin)
53 {
54  assert(is_open());
55  if (fseek(file, offset, origin) != 0) setstate(failbit);
56  return good();
57 }
58 
60 {
61  const long curPos = ftell(file);
62  if (curPos == -1) setstate(failbit);
63  seek(0, end);
64  const long size = ftell(file);
65  if (size == -1) setstate(failbit);
66  // Reset the file position even if the previous commands failed. Do not fail if position was
67  // invalid
68  if (curPos != -1 && !seek(curPos, beg)) setstate(failbit);
69  return size;
70 }
71 
73 {
74  const int c = fgetc(file);
75  if (c == EOF) { setstate(failbit | eofbit); }
76  return c;
77 }
78 }
bool seek(long offset, seekdir origin) override
Change the pointer of the stream to a given position.
Definition: FileStream.cpp:52
long size() override
Computes the size of the file.
Definition: FileStream.cpp:59
int getc() override
Read one byte from the stream.
Definition: FileStream.cpp:72
size_t read(void *buffer, size_t size) override
Read data from the stream.
Definition: FileStream.cpp:29
long tell() override
Return the current position of the stream pointer.
Definition: FileStream.cpp:42