nstool/lib/libfnd/source/io.cpp

116 lines
2.3 KiB
C++
Raw Normal View History

#include <fnd/io.h>
2017-07-02 15:18:59 +00:00
using namespace fnd;
static const std::string kModuleName = "IO";
2017-07-02 15:18:59 +00:00
static const size_t kBlockSize = 0x100000;
void io::readFile(const std::string& path, MemoryBlob & blob)
2017-07-02 15:18:59 +00:00
{
FILE* fp;
size_t filesz, filepos;
if ((fp = fopen(path.c_str(), "rb")) == NULL)
{
throw Exception(kModuleName, "Failed to open \"" + path + "\"");
}
fseek(fp, 0, SEEK_END);
filesz = ftell(fp);
rewind(fp);
try {
blob.alloc(filesz);
}
catch (const fnd::Exception& e)
2017-07-02 15:18:59 +00:00
{
fclose(fp);
throw fnd::Exception(kModuleName, "Failed to allocate memory for file: " + std::string(e.what()));
2017-07-02 15:18:59 +00:00
}
for (filepos = 0; filesz > kBlockSize; filesz -= kBlockSize, filepos += kBlockSize)
{
fread(blob.getBytes() + filepos, 1, kBlockSize, fp);
2017-07-02 15:18:59 +00:00
}
if (filesz)
{
fread(blob.getBytes() + filepos, 1, filesz, fp);
2017-07-02 15:18:59 +00:00
}
fclose(fp);
}
void fnd::io::readFile(const std::string& path, size_t offset, size_t len, MemoryBlob& blob)
{
FILE* fp;
size_t filesz, filepos;
if ((fp = fopen(path.c_str(), "rb")) == NULL)
{
throw Exception(kModuleName, "Failed to open \"" + path + "\": does not exist");
}
fseek(fp, 0, SEEK_END);
filesz = ftell(fp);
rewind(fp);
fseek(fp, offset, SEEK_SET);
if (filesz < len || filesz < offset || filesz < (offset + len))
{
throw Exception(kModuleName, "Failed to open \"" + path + "\": file to small");
}
try
{
blob.alloc(len);
} catch (const fnd::Exception& e)
{
fclose(fp);
throw fnd::Exception(kModuleName, "Failed to allocate memory for file: " + std::string(e.what()));
}
for (filepos = 0; len > kBlockSize; len -= kBlockSize, filepos += kBlockSize)
{
fread(blob.getBytes() + filepos, 1, kBlockSize, fp);
}
if (len)
{
fread(blob.getBytes() + filepos, 1, len, fp);
}
fclose(fp);
}
void io::writeFile(const std::string& path, const MemoryBlob & blob)
2017-07-02 15:18:59 +00:00
{
writeFile(path, blob.getBytes(), blob.getSize());
2017-07-05 09:17:04 +00:00
}
2018-03-22 05:26:22 +00:00
void io::writeFile(const std::string & path, const byte_t * data, size_t len)
2017-07-05 09:17:04 +00:00
{
FILE* fp;
size_t filesz, filepos;
if ((fp = fopen(path.c_str(), "wb")) == NULL)
{
throw Exception(kModuleName, "Failed to open \"" + path + "\"");
}
filesz = len;
2017-07-02 15:18:59 +00:00
2017-07-05 09:17:04 +00:00
for (filepos = 0; filesz > kBlockSize; filesz -= kBlockSize, filepos += kBlockSize)
{
fwrite(data + filepos, 1, kBlockSize, fp);
}
if (filesz)
{
2017-07-05 15:36:59 +00:00
fwrite(data + filepos, 1, filesz, fp);
2017-07-05 09:17:04 +00:00
}
fclose(fp);
2017-07-02 15:18:59 +00:00
}