1

我有这个程序从 LBA(逻辑块地址)读取数据,但每次我提供的 LBA 编号,它都会给出相同的输出。

我如何验证它?

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <linux/fs.h>
//#include "common.h"

typedef unsigned long long int var64;


int getSectorSize(int handle)
{
        int sectorSize = 0;

        //get the physical sector size of the disk
        if (ioctl(handle, BLKSSZGET, &sectorSize)) {

                printf("getSectorSize: Reading physical sector size failed.\n");

                sectorSize = 512;
        }

        return sectorSize;
}



var64 readLBA(int handle, var64 lba, void* buf, var64 bytes)
{
        int ret = 0;
        int sectorSize = getSectorSize(handle);
        var64 offset = lba * sectorSize;

        printf("readFromLBA: entered.\n");

        lseek64(handle, offset, SEEK_SET);
        ret = read(handle, buf, bytes);
        if(ret != bytes) {

              printf("read LBA: read failed.\n");

                return -1;
        }

        printf("read LBA: retval: %lld.\n", ret);
        return ret;
}

int main()
{
  int sectorSize, fd;
  char buff[100];
  printf("Calling getSectorSize\n");

  fd = open("/dev/sda1", O_RDONLY);

  if(fd == -1)
  {
    printf("open /dev/sda1 failed");
    exit(1);
  }
  sectorSize = getSectorSize(fd);
  printf("Sector size = %u\n", sectorSize);
  memset(buff, 0, sizeof(buff)); 
  readLBA(fd, 1, buff, 2); // if i put the 2nd arg as -12378 gives same answer
}

这是输出:

sles10-sp3:~ # gcc getSectorSizeMain.c
getSectorSizeMain.c: In function ‘main’:
getSectorSizeMain.c:75: warning: incompatible implicit declaration of built-in function ‘memset’
sles10-sp3:~ # ./a.out
Calling getSectorSize
Sector size = 512
read LBA: entered.
read LBA: retval: 8589934594. // This is always constant, how to validate? If i tell to read an invalid LBA number like -123456 the answer remains same. How to validate?
4

1 回答 1

3

retval不包含您感兴趣的数据,但 read() 的字节数已存储到您的缓冲区中,因此它总是包含相同的值是很自然的。但是在您的测试输出中,您尝试使用“%lld”(long long int)打印它,即使它只是一个普通的 int,所以 printf 会将它的值与它在堆栈上找到的任何东西结合起来(注意 8589934594= =0x200000002 - 最后一个数字是你的价值,第一个可能是垃圾)。

您要检查/使用/任何内容的数据都在数组 buff 中。

于 2012-07-06T10:43:08.930 回答