source: trunk/src/sys/file.cpp @ 2363

Last change on this file since 2363 was 2363, checked in by sam, 7 years ago

sys: be more resilient if the file we try to read doesn’t exist.

  • Property svn:keywords set to Id
File size: 2.1 KB
Line 
1//
2// Lol Engine
3//
4// Copyright: (c) 2010-2013 Sam Hocevar <sam@hocevar.net>
5//   This program is free software; you can redistribute it and/or
6//   modify it under the terms of the Do What The Fuck You Want To
7//   Public License, Version 2, as published by Sam Hocevar. See
8//   http://www.wtfpl.net/ for more details.
9//
10
11#if defined HAVE_CONFIG_H
12#   include "config.h"
13#endif
14
15#include "core.h"
16
17namespace lol
18{
19
20class FileData
21{
22    friend class File;
23
24    void Open(String const &file, FileAccess mode)
25    {
26#if __CELLOS_LV2__
27#elif HAVE_STDIO_H
28        /* FIXME: no modes, no error checking, no nothing */
29        m_fd = fopen(file.C(), "r");
30#endif
31    }
32
33    String ReadString()
34    {
35        String ret;
36#if __CELLOS_LV2__
37#elif HAVE_STDIO_H
38        while (m_fd && !feof(m_fd))
39        {
40            char buf[BUFSIZ];
41            size_t count = fread(buf, 1, BUFSIZ, m_fd);
42            if (count <= 0)
43                break;
44
45            int oldsize = ret.Count();
46            ret.Resize(oldsize + count);
47            memcpy(&ret[oldsize], buf, count);
48        }
49#endif
50        return ret;
51    }
52
53    void Close()
54    {
55#if __CELLOS_LV2__
56#elif HAVE_STDIO_H
57        if (m_fd)
58            fclose(m_fd);
59        m_fd = NULL;
60#endif
61    }
62
63#if __CELLOS_LV2__
64#elif HAVE_STDIO_H
65    FILE *m_fd;
66#endif
67    Atomic<int> m_refcount;
68};
69
70File::File()
71  : m_data(new FileData)
72{
73    ++m_data->m_refcount;
74}
75
76File::File(File const &that)
77  : m_data(that.m_data)
78{
79    ++m_data->m_refcount;
80}
81
82File &File::operator =(File const &that)
83{
84    if (this == &that)
85        return *this;
86
87    int refcount = --m_data->m_refcount;
88    if (refcount == 0)
89    {
90        m_data->Close();
91        delete m_data;
92    }
93
94    m_data = that.m_data;
95    ++m_data->m_refcount;
96
97    return *this;
98}
99
100File::~File()
101{
102    int refcount = --m_data->m_refcount;
103    if (refcount == 0)
104    {
105        m_data->Close();
106        delete m_data;
107    }
108}
109
110void File::Open(String const &file, FileAccess mode)
111{
112    return m_data->Open(file, mode);
113}
114
115String File::ReadString()
116{
117    return m_data->ReadString();
118}
119
120void File::Close()
121{
122    m_data->Close();
123}
124
125} /* namespace lol */
126
Note: See TracBrowser for help on using the repository browser.