从Linux磁盘读取扇区时fread返回0

时间:2020-06-28 10:09:11

标签: c linux ubuntu

我正在尝试从Ubuntu上的 / dev / sda 磁盘读取一个扇区,但是fread总是返回0,我似乎无法理解为什么这样做, 这是读取扇区的代码:


    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <sys/types.h>

 void read_sector(char *physical_disk, int num_sec) {
     char *diskName = "/dev/";
     char *ch1 = strstr(physical_disk,"sd");
     char *ch2 = strstr(physical_disk,"hd");
     if((ch1==NULL) && (ch2 == NULL)) {
        printf("Error, that is not a physical disk's name. \n");
        }
     else {
           int sect,n;
           int len = strlen(diskName) + strlen(physical_disk) + 2;
           char *str = (char*)malloc(len);
           strcpy(str,diskName);
           unsigned char buffer[512];
           long int sec = 512*num_sec;
           FILE *disk = NULL;
           strcat(str, physical_disk);
           disk = fopen(diskName, "rb");
           if (disk==NULL) printf("error, disk can't be opened \n");
           else {
                 sect = fseek(disk, sec, SEEK_SET);
                 if(sect != 0) printf("fseek error %d \n", sect);
                 else {
                       n = fread(buffer,512,1,disk);                        
                       if(n<=0) printf("fread error %d \n", n);
                       else printf("number of elements read : %d \n", n);
                      }
                }
                fclose(disk)
          }

}

int main(int argc, char const *argv[])
{
  read_sector("sda", 3);
  return(0);
}
  

关于为什么它返回0的任何想法?提前非常感谢您!

2 个答案:

答案 0 :(得分:1)

我还没有编译这段代码,因为它只是片段。但是您是否有权实际阅读设备?

您可以使用以下命令执行此操作。

id

uid=1001(user) gid=1001(user) groups=1001(user),27(sudo)

user@host01:~$ ls -la /dev/sda
brw-rw---- 1 root disk 253, 0 Jun 1 01:46 /dev/sda

user@host01:~$ dd if=/dev/sda of=/dev/null

dd: failed to open '/dev/sda': Permission denied

如果您排除许可,那么我们可以进一步查看代码。

答案 1 :(得分:0)

您在fread()中有一个错字。应该是buffer,而不是buffe