Advertisement
Guest User

Untitled

a guest
Jul 21st, 2020
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.09 KB | None | 0 0
  1. #define _LARGEFILE64_SOURCE /* See feature_test_macros(7) */
  2. #include <stdio.h>
  3. #include <errno.h>
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. #include <sys/types.h>
  7. #include <unistd.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include <math.h>
  11. #include <limits.h>
  12.  
  13. #define SECTOR_SIZE 512
  14.  
  15. /*
  16. Writes a test pattern, 1 sector in size, to a disk. Careful: destructive!
  17.  
  18. lseek64 allows the use of very long offsets.
  19. Specifying _LARGEFILE64_SOURCE is required for off_t used by lseek
  20. to be of 64 bit.
  21.  
  22. for more infos:
  23. $ man 3 lseek64
  24. */
  25.  
  26. int writelba(int fd, long offset, char* buf, int buf_size){
  27.     //write to fd at offset and sync
  28.  
  29.     lseek64(fd, offset, SEEK_SET);
  30.     if (errno > 0) return errno;
  31.     write(fd, buf, buf_size);
  32.     if (errno > 0) return errno;
  33.  
  34.     sync(); //to make sure it isn't cached in RAM
  35.  
  36.     return errno;
  37. }
  38.  
  39. int readlba(int fd, long offset, char* buf, int buf_size){
  40.     //read from fd at offset
  41.  
  42.     lseek64(fd, offset, SEEK_SET);
  43.     if (errno > 0) return errno;
  44.  
  45.     read(fd, buf, buf_size);
  46.     if (errno > 0) return errno;
  47.  
  48.     return errno;
  49. }
  50.  
  51. int main (void){
  52.     int fd;
  53.     char buf[SECTOR_SIZE] = {0};
  54.     memset(&buf, 0x64, sizeof(buf)/sizeof(char)); //initalise buf with a pattern
  55.     char result[SECTOR_SIZE] = {0};
  56.     int error = 0;
  57.     long sector = 1306638144;
  58.     long offset = sector*SECTOR_SIZE; //seek offset works with bytes
  59.  
  60.     fd = open("/dev/sdb", O_RDWR);
  61.     if (fd < 0){
  62.         printf("Failed opening file descriptor: %d", errno);
  63.         exit(errno);
  64.     }
  65.  
  66.     printf("Testing sector: %ld\n", sector);
  67.  
  68.     error = writelba(fd, offset, buf, sizeof(buf)/sizeof(char));
  69.     if (error > 0){
  70.         printf("Error while writing: %d\n", error);
  71.         exit(error);
  72.     }
  73.  
  74.     error = readlba(fd, offset, result, sizeof(result)/sizeof(char));
  75.     if (error > 0){
  76.         printf("Error while reading: %d\n", error);
  77.         exit(error);
  78.     }
  79.  
  80.     //print out what was read
  81.     printf("test pattern: %02x\nresult:\n", buf[0]);
  82.     for(int i = 0; i < 512; i++){
  83.         printf("%02x ", result[i]);
  84.     }
  85.     printf("\n");
  86.  
  87.     //to externally check this result: dd if=/dev/sdb of=/tmp/bin bs=512 count=1 skip=<LBA> && xxd /tmp/bin
  88.    
  89.  
  90.     exit(0);
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement