linux进行分区的代码,Linux 分区程序代码实例

#include

#include

#include

#include

#include

#include

#include

#include

#include

typedef unsigned char BYTE;

typedef unsigned short WORD;

typedef unsigned long DWORD;

typedef long LONG;

#pragma pack(1)

struct _dpt{

BYTE flag;

BYTE phy_sec_start[3];

BYTE type;

BYTE phy_sec_end[3];

DWORD logic_sec;

DWORD sec_cnt;

}DPT;

struct _mbr_sec{

BYTE code[446];

struct _dpt dpt[4];

WORD tag;

}MBR_SEC;

void logic2physic(BYTE * physic_sec,DWORD logic_sec)

{

physic_sec[0] = (logic_sec % 16065) / 63;

physic_sec[1] = ((logic_sec % 16065) % 63 + 1) &

0x3F;

physic_sec[1] |= ((logic_sec / 16065) & 0x300)

>> 2;

physic_sec[2] = (logic_sec / 16065) & 0xFF;

}

int main()

{

struct _mbr_sec mbr;

int sec_total;

int sec_start;

int sec_count;

char dev_file[128];

printf("Please type in the device filename which you need to

partition(such as '/dev/sda'):\n");

scanf("%s",dev_file);

int fd = open(dev_file, O_RDWR);

if(fd<2)

{

printf("Open /dev/sdb error.\n");

exit(-1);

}

ioctl(fd,BLKGETSIZE,&sec_total);

printf("TotalSize:%d sector.(512bytes/per sec)\n Please type in the

logic sector position:",sec_total);

scanf("%d",&sec_start);

printf("Please type in the logic count:");

scanf("%d",&sec_count);

mbr.tag = 0xaa55;

mbr.dpt[0].flag = 0;

mbr.dpt[0].type = 0x83;

mbr.dpt[0].sec_cnt = sec_start;

mbr.dpt[0].logic_sec = sec_count;

memset((BYTE *)&mbr.dpt[1], 0, sizeof(struct

_dpt)*3);

logic2physic(mbr.dpt[0].phy_sec_start,mbr.dpt[0].logic_sec);

logic2physic(mbr.dpt[0].phy_sec_end,mbr.dpt[0].logic_sec +

mbr.dpt[0].sec_cnt);

int n = write(fd,(BYTE *)&mbr,sizeof(struct

_mbr_sec));

if(n < sizeof(struct _mbr_sec))

printf("problem occor!\n");

ioctl(fd,BLKRRPART,NULL);

close(fd);

printf("write sdb partition table succeed.\n");

return 0;

}