介绍

在写裸机系统的时候,需要用到的从U盘启动到系统的情况,这时候
写一个U盘写入小工具很有必要,下面是将引导程序写入U盘的简单代码

假如已经有一个boot.bin的引导程序,需要写入U盘。

write-mbr.c

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <fcntl.h>
#include <stdio.h>
int main(int argc,char*argv[]){
    int dev_flag,file_flag;
    unsigned char buffer[512];
    file_flag = open("./boot.bin",O_RDONLY);
    if(file_flag == -1){
        perror("failed to read file boot");
    return -1;
}
    read(file_flag,buffer,510);
    close(file_flag);
    buffer[510] =0x55;
    buffer[511] =0xaa;
    dev_flag = open("/dev/sda",O_RDWR);
    if(dev_flag == -1){
        perror("failed to open device /dev/sda");
        return -1;
    }
    write(dev_flag,buffer,512);
    close(dev_flag);
    puts("successful.");
return 0;
}

执行命令

1
gcc -o write-mbr write-mbr.c

在操作之前,备份好U盘里面的数据,写完后,U盘里面的数据就丢失了。
将U盘接入电脑,挂载到linux上
首先用命令 sudo fdisk -l 可以通过容量找到对应U盘的设备名称。
然后用命令 sudo mount /dev/sda /mnt/flash将U盘挂载到flash,注意该命令需要flash目录存在,不存在则要创建:

1
cd /mnt && sudo mkdir flash

最后执行 ./write-mbr ,shell返回successful,说明写入成功。

然后,卸载设备

将U盘拔出,插入到另外一台测试电脑,并通过BIOS将启动项改为U盘优先。