c把bin二进制文件写入磁盘任意扇区

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/c5113620/article/details/84061600

使用nasm编译好bootloader的bin文件,写入磁盘第一扇区

//编译
nasm -f bin boot.asm -o boot.bin
// 然后以【管理员权限】运行下面编译的c程序
PHYSICALDRIVE3 后面的数字,表示磁盘序号,可以右键看--此电脑(我的电脑)--管理--磁盘管理,下面写的,磁盘0,磁盘1
/*读取asm编译好的bin字节文件,写入加载的vhd磁盘扇区
**需要管理员权限运行
*/

#include <Windows.h>
#include <stdio.h>

//存放扇区内容
unsigned char container[512];

//参数:输出的字符串指针,开始位置,长度
//返回值:读取的大小
DWORD ReadDisk(DWORD start, DWORD size)
{
	OVERLAPPED over = { 0 };
	over.Offset = start;
	HANDLE handle = CreateFile(TEXT("\\\\.\\PHYSICALDRIVE3"), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
	DWORD  Error = ERROR_SUCCESS;
	if (handle == INVALID_HANDLE_VALUE)
	{
		Error = GetLastError();
		//5 表示拒绝访问,没有权限
		wprintf(L"ReadDisk sector failed with error code %d\n", Error);
		return 0;
	}
	
	DWORD readsize;
	if (ReadFile(handle, container, size, &readsize, &over) == 0)
	{
		CloseHandle(handle);
		return 0;
	}

	//注意这里需要自己释放内存
	CloseHandle(handle);
	return readsize;
}

DWORD WriteDisk( DWORD start, DWORD size)
{
	OVERLAPPED over = { 0 };
	over.Offset = start;
	HANDLE handle = CreateFile(TEXT("\\\\.\\PHYSICALDRIVE3"), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
	DWORD  Error = ERROR_SUCCESS;
	if (handle == INVALID_HANDLE_VALUE)
	{
		Error = GetLastError();
		wprintf(L"WriteDisk sector failed with error code %d\n", Error);
		return 0;
	}
	DWORD writesize;
	if (WriteFile(handle, container, size, &writesize, &over) == 0)
	{
		CloseHandle(handle);
		return 0;
	}
	
	CloseHandle(handle);
	return writesize;
}

void readBin(DWORD start, DWORD size)
{
	OVERLAPPED over = { 0 };
	over.Offset = start;
	HANDLE handle = CreateFile(TEXT("\\\\.\\D:\\print.bin"), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
	DWORD  Error = ERROR_SUCCESS;
	if (handle == INVALID_HANDLE_VALUE)
	{
		Error = GetLastError();
		wprintf(L"readBin failed with error code %d\n", Error);
		return ;
	}
	DWORD readsize;
	if (ReadFile(handle, container, size, &readsize, &over) == 0)
	{
		CloseHandle(handle);
		return ;
	}
}

void printContainer()
{
	for (unsigned int i = 0; i < 512; i++) {
		printf("%02X ", container[i]);
	}
	printf("\n");
}

int main()
{
	DWORD len;

	len = ReadDisk(0, 512);
	printf("len:%d\n", len);
	printContainer();

	//读取bin字节
	readBin(0, 512);
	printf("bin:\n");
	printContainer();

	getchar();

	len = WriteDisk(0, 512);
	//写入字节数
	printf("len:%d\n", len);
	
	getchar();

	return 0;

}
展开阅读全文

没有更多推荐了,返回首页