2 * getsize.c --- get the size of a partition.
4 * Copyright (C) 1995, 1995 Theodore Ts'o.
7 * This file may be redistributed under the terms of the
8 * GNU Lesser General Public License.
12 #define _LARGEFILE_SOURCE
13 #define _LARGEFILE64_SOURCE
23 #ifdef HAVE_LINUX_FD_H
24 #include <sys/ioctl.h>
26 #endif /* HAVE_LINUX_FD_H */
27 #ifdef HAVE_SYS_DISKLABEL_H
28 #include <sys/ioctl.h>
29 #include <sys/disklabel.h>
30 #endif /* HAVE_SYS_DISKLABEL_H */
34 #if defined(__linux__) && defined(_IO) && !defined(BLKGETSIZE)
35 #define BLKGETSIZE _IO(0x12,96) /* return device size */
38 static int valid_offset(int fd, blkid_loff_t offset)
42 if (blkid_llseek(fd, offset, 0) < 0)
44 if (read(fd, &ch, 1) < 1)
50 * Returns the number of blocks in a partition
52 blkid_loff_t blkid_get_dev_size(int fd)
57 blkid_loff_t high, low;
59 struct floppy_struct this_floppy;
61 #ifdef HAVE_SYS_DISKLABEL_H
66 #endif /* HAVE_SYS_DISKLABEL_H */
69 if (ioctl(fd, BLKGETSIZE, &size) >= 0)
70 return (blkid_loff_t)size << 9;
73 if (ioctl(fd, FDGETPRM, &this_floppy) >= 0)
74 return (blkid_loff_t)this_floppy.size << 9;
76 #ifdef HAVE_SYS_DISKLABEL_H
77 part = strlen(file) - 1;
82 else if (ch >= 'a' && ch <= 'h')
87 if (part >= 0 && (ioctl(fd, DIOCGDINFO, (char *)&lab) >= 0)) {
88 pp = &lab.d_partitions[part];
90 return pp->p_size << 9;
92 #endif /* HAVE_SYS_DISKLABEL_H */
95 * OK, we couldn't figure it out by using a specialized ioctl,
96 * which is generally the best way. So do binary search to
97 * find the size of the partition.
100 for (high = 1024; valid_offset(fd, high); high *= 2)
102 while (low < high - 1)
104 const blkid_loff_t mid = (low + high) / 2;
106 if (valid_offset(fd, mid))
115 int main(int argc, char **argv)
121 fprintf(stderr, "Usage: %s device\n"
122 "Determine the size of a device\n", argv[0]);
126 if ((fd = open(argv[1], O_RDONLY)) < 0)
129 bytes = blkid_get_dev_size(fd);
130 printf("Device %s has %Ld 1k blocks.\n", argv[1], bytes >> 10);