From b25f0f167da0f74db53d259cd5517d4cb7cb0ab1 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 6 Nov 2023 14:00:14 -0800 Subject: [PATCH] revise rawdisk R/W API to set with offset and length --- include/rawdisk.h | 33 ++++++++++++--------------------- test/layer0.cpp | 4 ++-- 2 files changed, 14 insertions(+), 23 deletions(-) diff --git a/include/rawdisk.h b/include/rawdisk.h index ffc7f1c..efd45ed 100644 --- a/include/rawdisk.h +++ b/include/rawdisk.h @@ -14,7 +14,7 @@ class RawDisk{ off_t diskSize; public: - RawDisk(const char *directory){ + RawDisk(const char *directory) : fd(-1), dir(nullptr), numSectors(0), diskSize(0) { dir = directory; /*dir = strdup("/dev/vdc"); numSectors = 62914560; @@ -48,18 +48,13 @@ public: } } - int rawdisk_read(off_t blockNumber, char *buffer){ - // Calculate the offset in bytes - off_t offset = blockNumber * 512; - - // Move the file pointer to the desired block - if (lseek(fd, offset, SEEK_SET) == -1) { - perror("Error seeking to block"); + int rawdisk_read(off_t offset, char *buffer, size_t length) { + if (lseek(fd, offset, SEEK_SET) == (off_t)-1) { + perror("Error seeking to offset"); return -1; } - // Read a 512 byte-size block of data - ssize_t bytesRead = read(fd, buffer, 512); + ssize_t bytesRead = read(fd, buffer, length); if (bytesRead == -1) { perror("Error reading from device"); return -1; @@ -68,20 +63,16 @@ public: return 0; } - int rawdisk_write(off_t blockNumber, char *buffer){ - // Calculate the offset in bytes - off_t offset = blockNumber * 512; - - // Move the file pointer to the desired block - if (lseek(fd, offset, SEEK_SET) == -1) { - perror("Error seeking to block"); + // Write a specified number of bytes at a given byte offset + int rawdisk_write(off_t offset, char *buffer, size_t length) { + if (lseek(fd, offset, SEEK_SET) == (off_t)-1) { + perror("Error seeking to offset"); return -1; } - // Write a block of data - ssize_t bytesWrite = write(fd, buffer, 512); - if (bytesWrite == -1) { - perror("Error writing from device"); + ssize_t bytesWritten = write(fd, buffer, length); + if (bytesWritten == -1) { + perror("Error writing to device"); return -1; } diff --git a/test/layer0.cpp b/test/layer0.cpp index 3a73b0b..5e61c72 100644 --- a/test/layer0.cpp +++ b/test/layer0.cpp @@ -15,11 +15,11 @@ int main(int argc, char *argv[]) { //use number to substitute H->getnumSector(), getnumSectors() are not yest implemented for(off_t i = 0; i < 10; i++) { - H->rawdisk_write(i, buf); + H->rawdisk_write(i*512, buf, sizeof(buf));//Change write_API } //use number to substitute H->getnumSector(), getnumSectors() are not yest implemented for(off_t i = 0; i < 10; i++) { - H->rawdisk_read(i, readBuffer); + H->rawdisk_read(i*512, readBuffer, sizeof(readBuffer));//Change read_API assert(strncmp(readBuffer, buf, strlen(buf)) == 0); }