Глава – 11
Создание резервных копий
Зачем нужны резервные копии?
«Профилактика всегда лучше лечения». Резервное копирование также является важной частью предотвращения катастрофы данных, что может помочь нам преодолеть сбой диска или любой другой тип потери данных. В этой главе мы обсудим, как мы можем восстановить данные даже после некоторых серьезных сбоев диска, просто с помощью ранее сделанных резервных копий.
Восстановление, выполненное с помощью ранее сохраненных резервных копий, почти всегда составляет до 100 процентов, однако в некоторых конкретных случаях различные типы сбоев диска могут привести к различиям в результатах восстановления.
Восстановление данных с помощью резервных копий — довольно простой, быстрый и надежный процесс, который может дать наилучшие результаты, в то время как восстановление данных без резервных копий — сложный, запутанный и может занять много времени, и даже в этом случае во многих случаях мы опасаемся не получить 100 процентов данных.
Когда и что следует резервировать
На диске есть несколько различных областей, которые следует копировать один раз или с разной периодичностью. Следующая таблица дает представление о мерах полного резервного копирования и помогает выяснить, когда и что следует копировать:
Что нужно резервировать |
Когда необходимо резервное копирование |
Резервное копирование MBR |
После FDISK. MBR создается командой FDISK DOS. Вы можете сделать резервную копию MBR после FDISK, однако даже после ФОРМАТИРОВАНИЯ разделов, созданных FDISK, MBR остается неизмененной. |
Резервное копирование DBR |
После форматирования создайте резервную копию DBR для каждого логического диска. |
Резервное копирование записей FAT и каталогов. |
FAT и записи каталогов изменяются каждый раз, когда вы создаете или удаляете файлы или каталоги. Поэтому рекомендуется делать резервную копию ежедневно. |
Резервное копирование данных пользователя |
Следует делать регулярно. Этот тип резервного копирования приводит к созданию образа диска. Однако это занимает много времени, но большинство компаний, которые имеют очень конфиденциальные данные на своих дисках, любят тратить свое время на создание образа диска, поскольку таким образом они могут создать резервную копию всей информации, описанной выше. |
Кроме того, вам следует сделать аварийную загрузочную дискету для системы. Если произойдет какая-либо авария с данными на вашем жестком диске, вы сможете загрузить свою систему с помощью этой дискеты и проанализировать диск на наличие ошибок.
Резервное копирование MBR (главной загрузочной записи) и ее использование
Главная загрузочная запись (MBR) или иногда называемая главной таблицей разделов (MPT), содержит небольшую программу для загрузки и запуска активного (или загрузочного) раздела с жесткого диска. Главная загрузочная запись содержит информацию обо всех четырех основных разделах.
Подробное изучение MBR см. в главе «Логический подход к дискам и ОС», обсуждавшейся ранее в этой книге.
MBR находится в абсолютном секторе 0 или, можно сказать, в цилиндре 0, головке 0 и секторе 1. Он создается на жестком диске путем выполнения команды FDISK.EXE DOS.
Зачем делать резервную копию MBR:
MBR позволяет загрузочному сектору активного раздела получать управление при запуске системы.
После самотестирования при включении питания (POST) BIOS загружает MBR (главную загрузочную запись) с жесткого диска в память, а затем выполняет ее. Сначала MBR проверяет жесткий диск на наличие активного раздела, затем загружает загрузочную запись DOS (DBR) в память и передает управление коду загрузки операционной системы, а затем код загрузочной записи операционной системы загружает остальную часть операционной системы в память.
Поэтому мы можем сказать, что если MBR диска поврежден, жесткий диск практически мертв, и система полностью неспособна загрузить или запустить операционную систему. В таком состоянии все данные, хранящиеся на жестком диске, становятся недоступными. Обычно сообщения об ошибках отображаются следующим образом:
«Неверная таблица разделов» «Ошибка загрузки операционной системы» «Отсутствует операционная система»
Что можно восстановить с помощью резервной копии MBR?
Резервное копирование MBR может помочь вам избавиться от вышеуказанных сообщений об ошибках. С помощью резервного копирования можно устранить следующие проблемы:
- Ошибка загрузки операционной системы из-за поврежденного IPL (начального загрузчика программ)
- Потерянный основной раздел(ы)
- Поврежденная информация о разделе
- Неверное магическое число
Написание программы для создания резервной копии MBR:
/* Программа для создания резервной копии MBR */
#include <bios.h>
#include <stdio.h>
int main(пустота)
{
struct diskinfo_t dinfo; /* Структура для хранения
информация о параметрах диска */
результат int;
количество целых чисел=0;
char filename[80]; /* Сохраняет имя файла, заданное
User */
static char dbuf[512]; /* Data Buffer of 512 Bytes */
FILE *fp;
dinfo.drive = 0x80; /* drive number for First Hard
Disk */
dinfo.head = 0; /* disk head number */
dinfo.track = 0; /* track number */
dinfo.sector = 1; /* sector number */
dinfo.nsectors = 1; /* sector count */
dinfo.buffer = dbuf; /* data buffer */
printf("\n Enter The Filename and path to store the
Backup of MBR \n ");
gets(filename);
// Open The File to Store the MBR Backup \\
if((fp=fopen(filename,"wb"))==NULL)
{
printf("Could not Create File, Press any key to
Exit...");
getch();
exit(0);
}
printf("Attempting to read from Hard disk drive :\n");
//// Read the Specified Disk Sector \\\\
result = _bios_disk(_DISK_READ, &dinfo);
if ((result & 0xff00) == 0)
{
printf("Disk read from hard disk drive :
successful.\n");
/// Write 512 Bytes Of MBR to the File \\\\
while(count<512)
{
fprintf(fp,"%c",dbuf[count] & 0xff );
count++;
}
fclose(fp);
}
else
printf("Cannot read Hard Disk drive, status = 0x%02x\n", result);
return 0;
}
Comments on Program coding:
In the program coding given earlier, basically we are proceeding to perform the following tasks step by step:
- dinfo points to the diskinfo_t structure that contains the information of parameters required by the operation performed by the _bios_disk function.
- Since we want to read first sector of the disk therefore the location of the sector will be as follows:
Parameter |
What it means |
dinfo.drive = 0x80 |
It indicates the Physical drive 80H that is the first Hard disk drive. |
dinfo.head = 0 |
It points to head number 0 |
dinfo.track = 0 |
It points to track 0 |
dinfo.sector = 1 |
First sector of the floppy that is sector 1 |
dinfo.sector = 1 |
>Number of sectors to consider for read operation = 1 |
dinfo.buffer = dbuf |
Data buffer for the operation |
- Open a file stream of user given file name and path to store the backup of MBR of exact 512 bytes. The file name and path is stored in the character array filename.
- _bios_disk(_DISK_READ, &dinfo) reads the first sector of the hard disk (80H), specified by dinfo.
- The status returned, is stored in result that is used to display the message for successful operation or to display an error message on the screen if any error occurs.
Program to Restore the MBR from Backup:
If the MBR is corrupted any how, the program given next helps to restore the MBR Back.
It should always be kept in mind that the illegal use or use in lack of knowledge may of this program, may destroy your data information in the hard disk and may make the entire data inaccessible. You should be sure of what you are going to do. Otherwise you may more complicate the problem.
Program to Restore the MBR from Backup:
The Coding of the program is as follows:
/* Program to Restore the Backup of MBR From the Backup File */
#include <bios.h>
#include <stdio.h>
int main(void)
{
struct diskinfo_t dinfo;
int result;
int count=0;
char filename[80]; /* Stores the File name given
by User */
static char dbuf[512]; /* Data Buffer of 512 Bytes
*/
FILE *fp;
/* Get the user Input for MBR Backup file Path */
printf("\n Enter The Filename and path of Backup File of
MBR \n ");
gets(filename);
if((fp=fopen(filename,"rb"))==NULL)
{
printf("Could not open Backup File, Press any key
to Exit...");
getch();
exit(1);
}
/* MBR data should be of Exact 512 Bytes */
while(count<512)
{
fscanf(fp,"%c",&dbuf[count]);
count++;
}
fclose(fp);
printf("Attempting to Write to Hard disk drive :\n");
dinfo.drive = 0x80; /* drive number for First
Hard Disk */
dinfo.head = 0; /* disk head number */
dinfo.track = 0; /* track number */
dinfo.sector = 1; /* sector number */
dinfo.nsectors = 1; /* sector count */
dinfo.buffer = dbuf; /* data buffer */
result = _bios_disk(_DISK_WRITE, &dinfo);
if ((result & 0xff00) == 0)
{
printf("Restoring the Backup of MBR to The Disk
Sector: successful.\n");
}
else
printf("Cannot Write on Hard Disk drive, status =
0x%02x\n", result);
return 0;
}
Comments on Program coding:
In the program coding given above, basically we are proceeding to perform the following tasks step by step:
- dinfo points to the diskinfo_t structure that contains the information of parameters required by the operation performed by the _bios_disk function.
- Since we want to write on first sector of the disk therefore the location of the sector will be as follows:
Parameter |
What it means |
dinfo.drive = 0x80 |
It indicates the Physical drive 80H that is the first Hard disk drive. |
dinfo.head = 0 |
It points to head number 0 |
dinfo.track = 0 |
It points to track 0 |
dinfo.sector = 1 |
First sector of the floppy that is sector 1 |
dinfo.sector = 1 |
Number of sectors to consider for read operation = 1 |
dinfo.buffer = dbuf |
Data buffer for the operation |
- The file name and path of Backup of MBR, given by the user, is stored in the character array filename. It should be kept in mind that the MBR information should of Exact 512 bytes.
- _bios_disk(_DISK_WRITE, &dinfo) writes the data on the first sector of the hard disk (80H), specified by dinfo.
- The status returned, is stored in result that is used to display the message for successful operation or to display an error message on the screen if any error occurs.
Backup of DBR (DOS Boot Record) and its use
After the partition table, the DOS Boot Record (DBR) or sometimes called DOS Boot Sector is the second most important information on your hard drive.
For a Detailed study about DBR, refer the chapter, “Logical Approach to Disks and OS”, Discussed earlier in this book.
First logical sector of each DOS partition will contain a DOS Boot Record (DBR) or DOS Boot Sector. The job of the DBR is to load the operating system from the hard disk drive into the main memory of computer and give the system’s control to the loaded program.
The DOS Boot Record (DBR) for the first partition on a hard disk is usually found at Absolute Sector 63 (the 64th sector on the disk drive) or in CHS form we can say C–H–S = 0–1–1 for most drives.
However this location may vary depending upon the SPT (Sectors per Track) of the Drive. For example, on an old 245MB drive having only 31 SPT, the Boot Record was located on the 32nd sector (Absolute Sector 31).
The DBR is created by the FORMAT command of DOS, after partitioning is done using the FDISK command. The sector on which DBR resides becomes logical sector 1 of that particular partition for the DOS. The sector number used by DOS starts from the physical sector on which DBR is located.
The DBR contains a small program which is executed by the Master Boot Record (MBR) Executable program. All DOS partitions contain the program code to boot the machine i.e. load the operating system, but only that partition is given control by the Master Boot Record which as specified as active partition, in the partition table entry.
Why Backup DBR:
The DBR contains some important information about the disk geometry. This information is located in the first sector of every partition, such as:
- Jump Code + NOP
- OEM Name and Version
- Bytes Per Sector
- Sectors Per Cluster
- Reserved Sectors
- Number of Copies of FAT
- Maximum Root Directory Entries (but Not Available for FAT32)
- Number of Sectors in Partition Smaller than 32MB (Therefore Not Available for FAT32)
- Media Descriptor (F8H for Hard Disks)
- Sectors Per FAT (In Older FAT Systems and Not Available for FAT32)
- Sectors Per Track
- Number of Heads
- Number of Hidden Sectors in Partition
- Number of Sectors in Partition
- Number of Sectors Per FAT
- FAT Information Descriptor Flags
- Version of FAT32 Drive
- Cluster Number of the Start of the Root Directory
- Sector Number of the File System Information Sector
- Sector Number of the Backup Boot Sector
- Reserved
- Logical Drive Number of Partition
- Extended Signature (29H)
- Serial Number of Partition
- Volume Name of Partition
- FAT Name
- Executable Code
- Executable Marker or Magic Number (AAH 55H)
Generally, the following error messages are displayed on the screen:
“Disk boot failure”
“Non system disk or disk error”
“Invalid system disk or Disk I/O error”
“Replace the disk, and then press any key…”
What can be recovered with the Backup of DBR?
The back up of DBR may help you to get rid of the above Error messages. These Error Messages On the screen wait for the user to put a bootable disk with the above mentioned programs in the floppy drive and press a key.
The drive should be accessible if you boot the system from the bootable floppy or CD. Although the hard disk is not bootable, yet generally that should not affect access to the data of the disk drive. After booting the system with the bootable disk you can access the data.
By restoring the backup of DBR You can overcome the problems generated, as mentioned above.
Programs for Making and Restoring Backups of DBR:
The programs for making the Backups of DBR’s and restoring them are almost similar to the programs of MBR backup and to restore.
For example, if you are going to write the programs for making backup of DBR of First logical drive of the disk and to restore it back, the parameters specified by dinfo structure will be changed as follows:
Parameter |
What it means |
dinfo.drive = 0x80 |
It indicates the Physical drive 80H that is the first Hard disk drive> |
dinfo.head = 1 |
It points to head number 1 |
dinfo.track = 0 |
It points to track 0 |
dinfo.sector = 1 |
First sector of the floppy that is sector 1 |
dinfo.sector = 1 |
Number of sectors to consider for read operation = 1 |
dinfo.buffer = dbuf |
Data buffer for the operation |
Here we see that only the location of the sector to read/write is changed. Here the C-H-S is given as 0-1-1 as the DBR of first logical drive is stored here.
Complete Disk Imaging
This type of backup is getting more and more popular now days and most preferred by such organizations which have very sensitive data in their systems. They people can not take any chance of even a single percent of data loss.
Such organizations take their backups as entire disk image regularly. Though it is some time taking but gives you surety that you will miss nothing. Due to its increasing popularity, programmers have tried their best to make the disk imaging software more and more faster to minimize the time period taken by the imaging process.
Disk imaging is a good Idea because just by spending some tens of minutes you can get the ease of mind that you have backup of everything in your pocket. All of the factors like MBR, BDR, FATs, Root Directories are copied to the destination disk as it is.
What we need for disk imaging is an Identical (or almost Identical) destination hard disk, to our source hard disk in which we have our valuable data. One thing is always kept in mind that the destination disk should not be smaller then the source disk.
After taking the complete image, if you boot the system with the destination disk, in which you have taken the disk image, generally you will get all the data as it is.
Writing the program for complete disk imaging
The program for disk imaging has been given next. The Program uses the INT 13H extensions therefore it can support large disks too.
The program makes the image of first physical hard disk drive (0x80) to the second physical hard disk drive (0x81) therefore before making the backup image you should keep it in mind that all the data in destination disk (0x81) will be overwritten by the data of source disk (0x80) in sector by sector pattern.
The coding of the program has been given next:
/* Program to make the Image of First Hard Disk (0x80) to the second Hard Disk (0x81) */
#include<stdio.h>
#include<dos.h>
#include<conio.h>
/* Structure to be used by getdrivegeometry function using INT 13H Extension, Function Number 0x48. */
struct geometry
{
unsigned int size ; /* (call) size of Buffer */
unsigned int flags ; /* Information Flags */
unsigned long cyl ; /* Number of Physical
Cylinders on Drive */
unsigned long heads ;/* Number of Physical
Heads on Drive */
unsigned long spt ; /* Number of Physical
Sectors Per Track */
unsigned long sectors[2] ; /* Total Number of
Sectors on Drive */
unsigned int bps ; /* Bytes Per Sector */
} ;
/* Structure of Disk Address packet format, To be used by the Functions, readabsolutesectors and writeabsolutesectors */
struct diskaddrpacket
{
char packetsize ; /* Size of Packet, generally 10H */
char reserved ; /* Reserved (0) */
int blockcount ; /* Number of Blocks to Transfer */
char far *bufferaddress ; /* address to Transfer
Buffer */
unsigned long blocknumber[2] ; /* Starting Absolute
Block Number */
} ;
///// Function to get Drive Parameters \\\\\
unsigned long getdrivegeometry (int drive)
{
union REGS i, o ;
struct SREGS s ;
struct geometry g = { 26, 0, 0, 0, 0, 0, 0, 0 } ;
i.h.ah = 0x48 ; /* Function Number 0x48 of INT 13H
Extensions See the Comments
Below */
i.h.dl = drive; /* Drive Number */
i.x.si = FP_OFF ( (void far*)&g ) ;
s.ds = FP_SEG ( (void far*)&g ) ;
/* Invoke the specified function number of INT 13H extension with Segment Register Values */
int86x ( 0x13, &i, &o, &s ) ;
printf("\n Head = %lu, Sectors Per Track = %lu, Cylinder =
%lu\n", g.heads, g.spt, g.cyl);
/* If get drive Geometry function Fails, Display Error Message and Exit */
if(g.spt==0)
{
printf("\n Get Drive Geometry Function Fails....");
printf("\n Extensions Not Supported, Press any Key to
Exit...");
getch();
exit(1);
}
return *g.sectors; /* Return The Number of Sectors
on Drive */
}
////// Start Of Main \\\\\\
void main()
{
unsigned long loop=0, Sectors_in_HDD1=0, Sectors_in_HDD2=0;
unsigned char buffer[61440]; /* Data buffer of 61440
Bytes to Read/Write 120 Sectors of 512 Bytes at a time to save time. */
char choice;
clrscr();
/* If total no. of hard disks attached is less than two Display Error Message and Exit. */
if(((char)peekb(0x0040, 0x0075))<2)
{
printf("\n\n You Must Have At least Two Hard Disks
Attached to your Computer To Run This");
printf("\n Program. Press any Key to Exit... ");
getch();
exit(1);
}
/// Get parameters of First Hard Disk (0x80) \\\
Sectors_in_HDD1 = getdrivegeometry (0x80);
printf(" Total Sectors in First Hard Disk = %lu\n\n",
Sectors_in_HDD1);
/// Get Parameters of Second Hsrd Disk (0x81) \\\
Sectors_in_HDD2 = getdrivegeometry (0x81);
printf(" Total Sectors in Second Hard Disk = %lu\n\n",
Sectors_in_HDD2);
/// First Confirm, Then Proceed \\\
printf("\n All The Data in Second Hard Disk will be
lost !!!");
printf("\n Press \'Y\' to Continue, Else any key to
Exit... ");
choice = getche();
switch(choice)
{
case 'y':
case 'Y':
break;
default:
exit(0);
}
/* Destination should not be smaller than the Source */
if(Sectors_in_HDD2<Sectors_in_HDD1)
{
printf("\n\n Destination Disk should not be Smaller
than Source Disk");
printf("\n Press any Key to Exit...");
getch();
exit(0);
}
/* If Everything is okay, copy All the Sectors of the Source Disk to Destination Hard Disk */
gotoxy(10,15);printf("Copying Absolute Sector: ");
for(loop=0;loop< =Sectors_in_HDD1;loop=loop+120)
{
readabsolutesectors ( 0x80, loop, 120, buffer );
writeabsolutesectors ( 0x81, loop, 120, buffer );
gotoxy(36,15); printf("%ld",loop);
if(kbhit())
{
exit(0);
}
}
//// Show the Message of Completion \\\
printf("\n\n Disk Imaging is Now Completed, Press any Key
To Exit...");
getch();
}
//// End of main
Comments on Coding:
In the coding of the program given earlier, for disk Imaging We are proceeding by performing the Following tasks:
- The Structure, geometry is used by getdrivegeometry function using INT 13H Extension, Function Number 0x48. For a Detailed description on INT 13H Extensions, refer the chapter “Handling large hard disks”, Discussed earlier in this book.
The Data Types representing several parameters of the disk have the following meanings:
Data Type |
Size in Bytes |
Description |
unsigned int size |
2 Bytes |
Size of Buffer |
unsigned int flags |
2 Bytes |
Information Flags |
unsigned long cyl |
4 Bytes |
Number of Physical Cylinders on Drive |
unsigned long heads |
4 Bytes |
Number of Physical Heads on Drive |
unsigned long spt |
4 Bytes |
Number of Physical Sectors Per Track |
unsigned long sectors[2] |
8 Bytes |
Total Number of Sectors on Drive |
unsigned int bps |
2 Bytes |
Bytes Per Sector |
- The structure diskaddrpacket is used by the functions readabsolutesectors and writeabsolutesectors. The format of disk address packet has been given in the following table:
Data Type |
Size in Bytes |
Description |
char packetsize |
1 Byte |
Size of Packet, generally 10H |
char reserved |
1 Byte |
Reserved (0) |
int blockcount |
2 Bytes |
Number of Blocks to Transfer |
char far *bufferaddress |
4 Bytes |
address to Transfer Buffer |
unsigned long blocknumber[2] |
4 Bytes |
Starting Absolute Block Number |
- The getdrivegeometry function is used to get the parameters of specified Drive. The Function getdrivegeometry uses function number 0x48 of INT 13H Extensions.
The meaning of parameters has been described in the table given next:
Parameter |
What it means |
i.h.ah = 0x48 |
Function Number 0x48 of INT 13H Extensions |
i.h.dl = drive |
Drive Number |
i.x.si = FP_OFF ( (void far*)&g ) |
ds:si address to buffer for drive parameters as discussed earlier |
s.ds = FP_SEG ( (void far*)&g ) |
ds:si address to buffer for drive parameters as discussed earlier |
The int86x(0x13, &i, &o, &s) function invokes the interrupt 13H with segment register Values. The getdrivegeometry function returns the total number on drive.
- In the main() function, (char)peekb(0x0040, 0x0075); (the function peekb is Defined in DOS.H) returns the number of hard disks attached to the system.
The number of hard disks connected to the system is represented by the byte stored at memory location 0040H:0075H (Segment 0040H: Offset 0075H). If the number of hard disks connected to the system is less then two program shows the error message and exits.
Sectors_in_HDD1 = getdrivegeometry (0x80); gets the parameters of first hard disk (0x80) and returns the total number of sectors on first hard disk.
Similarly Sectors_in_HDD2 = getdrivegeometry (0x81); gets the parameters of second hard disk (0x81) and returns the total number of sectors on second hard disk.
After confirmation by the user to continue with imaging, first check the condition that the size of source hard disk should not be greater then the size of the destination hard disk. If the destination is smaller, Display the error message and exit.
If everything is going right, copy the sectors of the source disk to the destination disk. Here we are reading and writing 61440 Bytes (120 sectors with each of 512 Bytes) at a time to make the imaging process faster.
If you want to use more sectors at a time, even beyond the limit of 64K, you can do it by using “huge Pointer” in large memory model. The Example of Specification is as follows:
char huge array[100000L];
- The Function, readabsolutesectors ( 0x80, loop, 120, buffer ); reads the 120 sectors of first hard disk (0x80), starting from the sector number specified by unsigned long integer loop and store the data in data buffer.
- The Function, writeabsolutesectors ( 0x81, loop, 120, buffer ); writes the data of data buffer to 120 sectors of second hard disk (0x81), starting from the sector number specified by unsigned long integer loop.
The coding of the functions readabsolutesectors ( ) and writeabsolutesectors ( ) have been given next:
//// Function to read absolute sector(s) \\\\
int readabsolutesectors ( int drive,
unsigned long sectornumber,
int numofsectors,
void *buffer )
{
union REGS i, o ;
struct SREGS s ;
struct diskaddrpacket pp ;
pp.packetsize = 16 ; /* packet size = 10H */
pp.reserved = 0 ; /* Reserved = 0 */
pp.blockcount = numofsectors ; /* Number of sectors
to read */
/* for Data buffer */
pp.bufferaddress = (char far*) MK_FP ( FP_SEG((void
far*)buffer), FP_OFF((void far*)buffer));
pp.blocknumber[0] = sectornumber ; /* Sector number
to read */
pp.blocknumber[1] = 0 ; /* Block number */
i.h.ah = 0x42 ; /* Function Number*/
i.h.dl = drive ; /* Physical Drive Number */
i.x.si = FP_OFF ( (void far*)&pp ) ; /* ds:si for
buffer Parameters */
s.ds = FP_SEG ( (void far*)&pp ) ; /* ds:si for
buffer Parameters */
/* Invoke the specified Function of INT 13H with segment register values */
int86x ( 0x13, &i, &o, &s ) ;
if ( o.x.cflag==1)
return 0 ; /*failure */
else
return 1 ; /* success */
}
//// Function to Write Absolute Sector(s) \\\\
int writeabsolutesectors ( int drive,
unsigned long sectornumber,
int numofsectors,
void *buffer )
{
профсоюз РЕГС i, o ;
структура SREGS s ;
struct diskaddrpacket pp ;
pp.packetsize = 16 ; /* Размер пакета = 10H */
pp.reserved = 0 ; /* Зарезервировано = 0 */
pp.blockcount = numofsectors ; /* Количество секторов
будет написано */
/* для буфера данных */
pp.bufferaddress = (char far*) MK_FP ( FP_SEG((void
дальний*)буфер), FP_OFF((void дальний*)буфер));
pp.blocknumber[0] = sectornumber ;/* Номер сектора
будет написано */
pp.blocknumber[1] = 0 ; /* Номер блока = 0 */
ihah = 0x43 ; /* Номер функции */
ihal = 0x00 ; /* Запись флагов, см.
комментарии */
ihdl = drive ; /* Номер физического диска*/
/* ds:si для параметров буфера */
ixsi = FP_OFF ( (void far*)&pp ) ;
/* ds:si для параметров буфера */
s.ds = FP_SEG ( (void far*)&pp ) ;
/* Вызвать указанную функцию INT 13H со значениями сегментного регистра */
int86x ( 0x13, &i, &o, &s ) ;
если ( oxcflag == 1)
возврат 0 ; /* неудача */
еще
возврат 1 ; /* успех */
}
Комментарии по кодированию:
Параметры, используемые обеими функциями, имеют следующие значения:
Параметр |
Размер в байтах |
Описание |
pp.packetsize = 16 ; |
1 байт |
Размер пакета = 10H |
pp.зарезервировано = 0 ; |
1 байт |
Зарезервировано = 0 |
pp.blockcount = numofsectors ; |
2 байта |
Количество секторов для чтения |
pp.bufferaddress = (char far*) MK_FP ( FP_SEG((void far*)buffer), FP_OFF((void far*)buffer)); |
----- |
для буфера данных или буфера передачи |
pp.blocknumber[0] = номер_сектора; |
4 байта |
Номер сектора для чтения/записи (обычно нам нужен только он). Только отдельно. Может поддерживать до 2,1 терабайт. |
pp.номер_блока[1] = 0 ; |
4 байта |
Номер блока. Используйте его, если обращаетесь к диску размером более 2,1 терабайта. |
ихах = 0x42; или i.h.ah = 0x43 ; |
2 байта |
Функция Количество расширений INT 13H |
ihal = 0x00 ; |
1 байт |
Флаги записи используются только в функции записи, 00H, 01H используются для записи без проверки, а 02H используется для записи с проверкой. |
ihdl = привод ; |
2 байта |
Номер физического диска |
ixsi = FP_OFF ( (void far*)&pp ) ; |
------ |
ds:si для параметров буфера |
s.ds = FP_SEG ( (void far*)&pp ) ; |
------ |
ds:si для параметров буфера |
int86x ( 0x13, &i, &o, &s ) ; |
------ |
Вызвать указанную функцию INT 13H со значениями сегментного регистра |