Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _LARGEFILE64_SOURCE /* See feature_test_macros(7) */
- #include <stdio.h>
- #include <errno.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <sys/types.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <string.h>
- #include <math.h>
- #include <limits.h>
- #define SECTOR_SIZE 512
- /*
- Writes a test pattern, 1 sector in size, to a disk. Careful: destructive!
- lseek64 allows the use of very long offsets.
- Specifying _LARGEFILE64_SOURCE is required for off_t used by lseek
- to be of 64 bit.
- for more infos:
- $ man 3 lseek64
- */
- int writelba(int fd, long offset, char* buf, int buf_size){
- //write to fd at offset and sync
- lseek64(fd, offset, SEEK_SET);
- if (errno > 0) return errno;
- write(fd, buf, buf_size);
- if (errno > 0) return errno;
- sync(); //to make sure it isn't cached in RAM
- return errno;
- }
- int readlba(int fd, long offset, char* buf, int buf_size){
- //read from fd at offset
- lseek64(fd, offset, SEEK_SET);
- if (errno > 0) return errno;
- read(fd, buf, buf_size);
- if (errno > 0) return errno;
- return errno;
- }
- int main (void){
- int fd;
- char buf[SECTOR_SIZE] = {0};
- memset(&buf, 0x64, sizeof(buf)/sizeof(char)); //initalise buf with a pattern
- char result[SECTOR_SIZE] = {0};
- int error = 0;
- long sector = 1306638144;
- long offset = sector*SECTOR_SIZE; //seek offset works with bytes
- fd = open("/dev/sdb", O_RDWR);
- if (fd < 0){
- printf("Failed opening file descriptor: %d", errno);
- exit(errno);
- }
- printf("Testing sector: %ld\n", sector);
- error = writelba(fd, offset, buf, sizeof(buf)/sizeof(char));
- if (error > 0){
- printf("Error while writing: %d\n", error);
- exit(error);
- }
- error = readlba(fd, offset, result, sizeof(result)/sizeof(char));
- if (error > 0){
- printf("Error while reading: %d\n", error);
- exit(error);
- }
- //print out what was read
- printf("test pattern: %02x\nresult:\n", buf[0]);
- for(int i = 0; i < 512; i++){
- printf("%02x ", result[i]);
- }
- printf("\n");
- //to externally check this result: dd if=/dev/sdb of=/tmp/bin bs=512 count=1 skip=<LBA> && xxd /tmp/bin
- exit(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement