00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011 #include "xrb_bitcachedfile.hpp"
00012
00013 #include <string.h>
00014
00015 namespace Xrb
00016 {
00017
00018 void BitCachedFile::Open (
00019 char const *const path,
00020 char const *const mode)
00021 {
00022 ASSERT1(path != NULL);
00023 ASSERT1(mode != NULL);
00024 ASSERT1(!IsOpen());
00025
00026 if (strlen(path) == 0)
00027 {
00028 SetError(IOE_INVALID_FILENAME);
00029 return;
00030 }
00031
00032
00033
00034 bool mode_r = strchr(mode, 'r') != NULL;
00035 bool mode_w = strchr(mode, 'w') != NULL;
00036 bool mode_a = strchr(mode, 'a') != NULL;
00037 Uint32 mode_count = mode_r ? 1 : 0 +
00038 mode_w ? 1 : 0 +
00039 mode_a ? 1 : 0;
00040
00041
00042 bool mode_b = strchr(mode, 'b') != NULL;
00043 bool mode_t = strchr(mode, 't') != NULL;
00044 Uint32 type_count = mode_b ? 1 : 0 +
00045 mode_t ? 1 : 0;
00046 if (mode_count != 1 || type_count != 1)
00047 {
00048 SetError(IOE_INVALID_FILE_OPEN_MODE);
00049 return;
00050 }
00051
00052 m_file_handle = fopen(path, mode);
00053 if (m_file_handle == NULL)
00054 {
00055 SetError(IOE_UNABLE_TO_OPEN_FILE);
00056 return;
00057 }
00058
00059 m_path = path;
00060 m_mode = mode;
00061
00062 if (mode_r)
00063 OpenForReading();
00064 else
00065 OpenForWriting();
00066 }
00067
00068 void BitCachedFile::Close ()
00069 {
00070 ASSERT1(IsOpen());
00071
00072 BitCache::Close();
00073
00074 if (fclose(m_file_handle) != 0)
00075 ASSERT1(false && "fclose() failed.");
00076
00077 m_file_handle = NULL;
00078 m_path.clear();
00079 m_mode.clear();
00080 }
00081
00082 Uint32 BitCachedFile::FlushBytes (
00083 Uint8 const *const bytes_to_flush,
00084 Uint32 const number_of_bytes_to_flush) const
00085 {
00086 ASSERT1(bytes_to_flush != NULL);
00087 ASSERT1(number_of_bytes_to_flush > 0);
00088 ASSERT1(IsOpen());
00089 ASSERT1(GetIODirection() == IOD_WRITE);
00090 ASSERT1(m_file_handle != NULL);
00091 Uint32 bytes_written =
00092 fwrite(
00093 bytes_to_flush,
00094 sizeof(Uint8),
00095 number_of_bytes_to_flush,
00096 m_file_handle);
00097
00098 return bytes_written;
00099 }
00100
00101 Uint32 BitCachedFile::RenewBytes (
00102 Uint8 *const bytes_to_renew,
00103 Uint32 const number_of_bytes_to_renew) const
00104 {
00105 ASSERT1(bytes_to_renew != NULL);
00106 ASSERT1(number_of_bytes_to_renew > 0);
00107 ASSERT1(IsOpen());
00108 ASSERT1(GetIODirection() == IOD_READ);
00109 ASSERT1(m_file_handle != NULL);
00110 Uint32 bytes_read =
00111 fread(
00112 bytes_to_renew,
00113 sizeof(Uint8),
00114 number_of_bytes_to_renew,
00115 m_file_handle);
00116
00117 return bytes_read;
00118 }
00119
00120 }