1 /* 2 * A file accessor employing a "host" file provided via the C library. 3 * 4 * Copyright (C) 2021 Paul Boddie <paul@boddie.org.uk> 5 * 6 * This program is free software; you can redistribute it and/or 7 * modify it under the terms of the GNU General Public License as 8 * published by the Free Software Foundation; either version 2 of 9 * the License, or (at your option) any later version. 10 * 11 * This program is distributed in the hope that it will be useful, 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 * GNU General Public License for more details. 15 * 16 * You should have received a copy of the GNU General Public License 17 * along with this program; if not, write to the Free Software 18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, 19 * Boston, MA 02110-1301, USA 20 */ 21 22 #include <stdio.h> 23 #include <string.h> 24 #include <sys/types.h> 25 #include <sys/stat.h> 26 27 #include "host_file_accessor.h" 28 29 HostFileAccessor::HostFileAccessor(const char *path, fileid_t fileid) 30 : Accessor(fileid), _path(path) 31 { 32 /* Initialise the size of the file. */ 33 34 struct stat buf; 35 36 if (!stat(_path, &buf)) 37 _size = buf.st_size; 38 else 39 _size = 0; 40 } 41 42 /* Return the size of the file. */ 43 44 offset_t HostFileAccessor::get_size() 45 { 46 return _size; 47 } 48 49 /* Update the size of the file. */ 50 51 void HostFileAccessor::set_size(offset_t size) 52 { 53 _size = size; 54 } 55 56 /* Perform any closing operation on the file. */ 57 58 void HostFileAccessor::close() 59 { 60 fclose(_fp); 61 } 62 63 /* Perform any opening operation on the file. */ 64 65 void HostFileAccessor::open() 66 { 67 _fp = fopen(_path, "r"); 68 } 69 70 /* Data transfer helper methods. */ 71 72 void HostFileAccessor::fill_populated(Flexpage *flexpage) 73 { 74 offset_t filepos = flexpage->base_offset; 75 offset_t addr = flexpage->base_addr; 76 77 /* Seek to the offset in the file. */ 78 79 fseek(_fp, filepos, SEEK_SET); 80 81 /* Tag the region with file state. */ 82 83 flexpage->region->fill(fileid, filepos); 84 85 /* Fill the region with file content. */ 86 87 size_t nread = fread((void *) addr, sizeof(char), flexpage->size, _fp); 88 89 /* Pad the flexpage with zero. */ 90 91 memset((void *) (addr + nread), 0, flexpage->size - nread); 92 } 93 94 void HostFileAccessor::flush_populated(Flexpage *flexpage) 95 { 96 flexpage->region->flush(); 97 } 98 99 // vim: tabstop=4 expandtab shiftwidth=4