1. 程式人生 > >c把bin二進位制檔案寫入磁碟任意扇區

c把bin二進位制檔案寫入磁碟任意扇區

使用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;

}