From 97d9ed131ae4fad7d54274cf5b74cf587b391bad Mon Sep 17 00:00:00 2001 From: Andrei Karas Date: Wed, 29 Mar 2017 01:49:04 +0300 Subject: Impliment loadFile in each virtual file system. --- src/fs/virtfs/virtfsdir.cpp | 62 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) (limited to 'src/fs/virtfs/virtfsdir.cpp') diff --git a/src/fs/virtfs/virtfsdir.cpp b/src/fs/virtfs/virtfsdir.cpp index 781182b8f..7521764fd 100644 --- a/src/fs/virtfs/virtfsdir.cpp +++ b/src/fs/virtfs/virtfsdir.cpp @@ -138,6 +138,7 @@ namespace VirtFsDir ptr->openRead = &VirtFsDir::openRead; ptr->openWrite = &VirtFsDir::openWrite; ptr->openAppend = &VirtFsDir::openAppend; + ptr->loadFile = &VirtFsDir::loadFile; } VirtFsFuncs *getFuncs() @@ -444,4 +445,65 @@ namespace VirtFsDir #endif // USE_FILE_FOPEN return pos < 0 || len < 0 || pos >= len; } + + char *loadFile(VirtFsEntry *restrict const entry, + const std::string &restrict filename, + int &restrict fileSize) + { + VirtDirEntry *const dirEntry = static_cast(entry); + const std::string path = entry->root + filename; + if (Files::existsLocal(path) == false) + return nullptr; + FILEHTYPE fd = FILEOPEN(path.c_str(), + FILEOPEN_FLAG_READ); + if (fd == FILEHDEFAULT) + { + reportAlways("VirtFs::loadFile file open error: %s", + filename.c_str()); + return nullptr; + } + + logger->log("Loaded %s/%s", + dirEntry->userDir.c_str(), + filename.c_str()); + +#ifdef USE_FILE_FOPEN + fseek(fd, 0, SEEK_END); + const long sz = ftell(fd); + fseek(fd, 0, SEEK_SET); + fileSize = static_cast(sz); +#else // USE_FILE_FOPEN + struct stat statbuf; + if (fstat(fd, &statbuf) == -1) + { + reportAlways("VirtFsDir::fileLength error."); + return -1; + } + fileSize = static_cast(statbuf.st_size); +#endif // USE_FILE_FOPEN + + // Allocate memory and load the file + char *restrict const buffer = new char[fileSize]; + if (fileSize > 0) + buffer[fileSize - 1] = 0; + +#ifdef USE_FILE_FOPEN + int cnt = fread(buffer, 1, fileSize, fd); +#else // USE_FILE_FOPEN + int cnt = ::read(fd, buffer, fileSize); +#endif // USE_FILE_FOPEN + + if (cnt <= 0) + { + delete [] buffer; + if (fd != FILEHDEFAULT) + FILECLOSE(fd); + return nullptr; + } + + if (fd != FILEHDEFAULT) + FILECLOSE(fd); + + return buffer; + } } // namespace VirtFs -- cgit v1.2.3-70-g09d2