1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
|
#include "lc_global.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include "lc_file.h"
lcMemFile::lcMemFile()
{
mGrowBytes = 1024;
mPosition = 0;
mBufferSize = 0;
mFileSize = 0;
mBuffer = nullptr;
}
lcMemFile::~lcMemFile()
{
Close();
}
void lcMemFile::Seek(qint64 Offset, int From)
{
if (From == SEEK_SET)
mPosition = Offset;
else if (From == SEEK_CUR)
mPosition += Offset;
else if (From == SEEK_END)
mPosition = mFileSize + Offset;
}
long lcMemFile::GetPosition() const
{
return (long)mPosition;
}
void lcMemFile::SetLength(size_t NewLength)
{
if (NewLength > mBufferSize)
GrowFile(NewLength);
if (NewLength < mPosition)
mPosition = NewLength;
mFileSize = NewLength;
}
size_t lcMemFile::GetLength() const
{
return mFileSize;
}
void lcMemFile::Close()
{
if (!mBuffer)
return;
mPosition = 0;
mBufferSize = 0;
mFileSize = 0;
free(mBuffer);
mBuffer = nullptr;
}
size_t lcMemFile::ReadBuffer(void* Buffer, size_t Bytes)
{
if (Bytes == 0 || mPosition > mFileSize)
return 0;
size_t BytesToRead;
if (mPosition + Bytes > mFileSize)
BytesToRead = mFileSize - mPosition;
else
BytesToRead = Bytes;
memcpy(Buffer, mBuffer + mPosition, BytesToRead);
mPosition += BytesToRead;
return BytesToRead;
}
size_t lcMemFile::WriteBuffer(const void* Buffer, size_t Bytes)
{
if (Bytes == 0)
return 0;
if (mPosition + Bytes > mBufferSize)
GrowFile(mPosition + Bytes);
memcpy(mBuffer + mPosition, Buffer, Bytes);
mPosition += Bytes;
if (mPosition > mFileSize)
mFileSize = mPosition;
return Bytes;
}
void lcMemFile::GrowFile(size_t NewLength)
{
if (NewLength <= mBufferSize)
return;
NewLength = ((NewLength + mGrowBytes - 1) / mGrowBytes) * mGrowBytes;
if (mBuffer)
{
unsigned char* NewBuffer = (unsigned char*)realloc(mBuffer, NewLength);
if (!NewBuffer)
return;
mBuffer = NewBuffer;
}
else
mBuffer = (unsigned char*)malloc(NewLength);
mBufferSize = NewLength;
}
char* lcMemFile::ReadLine(char* Buffer, size_t BufferSize)
{
int BytesRead = 0;
unsigned char ch;
if (BufferSize == 0)
return nullptr;
if (mPosition >= mFileSize)
return nullptr;
while ((--BufferSize))
{
if (mPosition == mFileSize)
break;
ch = mBuffer[mPosition];
mPosition++;
Buffer[BytesRead++] = ch;
if (ch == '\n')
break;
}
Buffer[BytesRead] = 0;
return Buffer;
}
|