Use CreateFile, ReadFile, WriteFile to read and write absolute sectors under Windows NT/2000/XP

Source: Internet
Author: User
Tags readfile

that is, when CreateFile open the file name designation: "\\.\device" is OK.
because the code is relatively short, so I do not make comments, I believe you can see the code to understand the meaning.
also read and write here is floppy disk a disk NO. 0 sector, if you want to read and write other sectors, you can use the API SetFilePointer.
The method of reading the sector (the following code demonstrates reading data from the No. 0 sector of a drive and writing to the file Boot.bin):
#include <windows.h>
#include <assert.h>
#include <stdio.h>
void Main ()
{
HANDLE hfile;
hfile = CreateFile ("\\\\.\\a:",
Generic_read,
File_share_read,
NULL,
open_existing,
0,
NULL);
assert (hfile && "CreateFile failed!");
pbyte pbuffer = (pbyte) malloc (+);
assert (pbuffer && "Allocate memory failed!");
DWORD Dwlen;
ReadFile (hfile, pbuffer, &dwlen, NULL);

FILE * FP;
fp = fopen ("Boot.bin", "WB");
assert (FP && "Open file failed!");
fwrite (pbuffer, 1, FP);
fclose (FP);
CloseHandle (hfile);
Free (pbuffer);
}
so the corresponding, the method of writing the sector is this way (the following code demonstrates reading data from Boot.bin to the No. 0 sector of the drive):
#include <windows.h>
#include <assert.h>
#include <stdio.h>
void Main ()
{
HANDLE hfile;
hfile = CreateFile ("\\\\.\\a:",
Generic_write,
File_share_write,
NULL,
open_existing,
0,
NULL);
assert (hfile && "CreateFile failed!");
pbyte pbuffer = (pbyte) malloc (+);
assert (pbuffer && "Allocate memory failed!");

FILE * FP;
fp = fopen ("Boot.bin", "RB");
assert (FP && "Open file failed!");
fread (pbuffer, 1, FP);
fclose (FP);

DWORD Dwlen;
WriteFile (hfile, pbuffer, &dwlen, NULL);
CloseHandle (hfile);
Free (pbuffer);
}

Use CreateFile, ReadFile, WriteFile to read and write absolute sectors under Windows NT/2000/XP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.