Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Get the size of an HD in Linux 1

Status
Not open for further replies.

666cartman

Programmer
Aug 27, 2002
20
DE
I finally found the solution:

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

void main ()

{
int fd;
int sector_size = 1;
long sectors;
long size;
struct hd_big_geometry g;
fd=open(&quot;/dev/hda&quot;,O_RDONLY);
if (ioctl(fd, HDIO_GETGEO_BIG_RAW, &g))return -1;
if (ioctl(fd, BLKGETSIZE, &sectors))return -1;
if (ioctl(fd, BLKSSZGET, &sector_size))return -1;

printf(&quot;sectorsize: %d sectors:
%ld\n&quot;,sector_size,sectors);
size=sectors/(1024/sector_size);

printf(&quot;size: %ld\n&quot;,size);

}


the Code is not perfect but it works, notice that it gets the real size of an hd from the driver. Of course it only works if you are root.
 
OK, on exit C will close all opened fd's
but is not good practice to left them opened!!
you could get problems.
give for flexibility, the /dev/???? as params to main.
i see no problems, setting root-setuid to a WELL written and
COMPILED exec, chmod 4511 <name>; chown 0 <name>
so everybody can get the infos.
 
sorry, i just forgot to enter the close in the post it is in my real prog, also are the params, i just posted a real slim code fragment, sorryy anout that
 
I think you may add :
close(fd);
before the application exit.
 
if (ioctl(fd, BLKGETSIZE, ¡±ors))return -1;
if (ioctl(fd, BLKSSZGET, ¡±or_size))return -1;

may be:
if (ioctl(fd, BLKGETSIZE,&sectors))
return ;
if (ioctl(fd, BLKSSZGET,&sector_size))
return ;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top