Recommanded Free YOUTUBE Lecture: <% selectedImage[1] %>

GetDisk Size

ioctl()을 이용해서 Disk의 크기를 얻어오는 간단한 함수, Linux(:12) 운영체제에서만 테스트 되었다.

원본 코드

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/fs.h>
#include <sys/time.h>
#include <sys/ioctl.h>

int getdevsize(char *devname)
{
  int fd;
  int blcks;
  int sects;
  fd = open(devname, O_RDONLY);
  if (fd < 0)
  {
    perror("error");
    return -1;
  }

  ioctl(fd, BLKGETSIZE, &blcks);
  ioctl(fd, BLKSSZGET, &sects);

  close(fd);
  return (blcks/1024) * sects;
}

사용방법

int main(int argc, char **argv)
{
  printf("%d\n", getdevsize(argv[1]));
}   

추가사항

모든 장치를 자동으로 검사하게 할 수도 있다. 이경우 /proc/devices를 읽어서 블럭장치의 목록을 만든다음, 해당하는 장치의 /proc정보를 읽어들여야 한다. 예를들어 ide블럭장치라면 /proc/ide, scsi라면 /proc/scsi의 하위디렉토리 정보를 읽어야 한다.