通过C++程序实现光驱的自动化刻录和读取


数字存储媒体快速发展的今天,光驱的使用已经不像以前那样普及了。但是在数据备份、安装软件和操作系统、旧设备兼容等领域还有在使用。

ISO文件格式

在刻录普通文件到光盘时,并不一定需要将它们制作成ISO文件。你可以使用光盘刻录软件直接添加文件到光盘中,而无需事先制作ISO文件。而如果你希望确保光盘上的文件与多个操作系统兼容或者需要创建一个可引导的光盘,那么制作成ISO文件可能是一个更好的选择。在这种情况下,你可以在刻录软件中选择制作ISO映像,然后再将该ISO文件刻录到光盘上。

制作成ISO文件的优点:
1.保持文件的完整性和一直性 2.兼容多个操作系统 3.可以跨平台使用 4.方便管理和存储

光盘的基本概念

Session(会话): 会话是光盘上的一个逻辑刻录单元。每次进行刻录,都会创建一个新的会话。
Track(轨道): 轨道是光盘上的一个圆形路径,沿着这个路径数据被刻录和读取。光盘上通常有许多并行的轨道,每个轨道都划分为一系列的扇区。
Sector(扇区): 扇区是光盘上最小的物理存储单元,是数据的基本单元。一个光盘被划分为许多扇区,每个扇区通常包含2048字节(2KB)的数据。

光盘种类特点

根据光盘的写入类型、用途、容量,光盘分为很多种类,详细分类如下:

CD(Compact Dis) 典型容量为700MB
1.CD-ROM(Read-Only Memory): 只读光盘 用于分发软件、应用和视频
2.CD-R(Recordable): 可以一次性写入, 写入之后不能修改,常用于备份音乐和数据
3.CD-RW(ReWritable): 可多次擦写和重写,适合频繁修改数据

DVD(Digital Versaatile Disc) 单层容量为4.7GB 双层容量为8.5GB
1.DVD-ROM: 类似于CD-ROM,只读光盘,用于电影、软件等的分发。
2.DVD-R: 一次写入型,用于备份和分发。
3.DVD+R: 一次写入型,与DVD-R相似。
4.DVD-RW: 可多次擦写和重写。
5.DVD+RW: 与DVD-RW类似。

Blu-ray Disc(BD) 单层容量为25GB 双层容量为50GB
1.BD-ROM: 用于高清电影和软件分发的一次写入型。
2.BD-R: 一次写入型,用于高容量数据备份。
BD-RE(Rewritable): 可多次擦写和重写,适用于频繁修改的数据。

HD DVD(已基本淘汰)
HD DVD-ROM: 用于高清电影和软件分发的一次写入型。
HD DVD-R: 一次写入型,用于备份和分发。
HD DVD-RW: 可多次擦写和重写。

Mini光盘
Mini CD 和 Mini DVD: 较小尺寸的光盘,用于特定设备和应用。

DVD+R光盘使用

这里以DVD+R光盘为例说明一下,光盘的使用和初始化,初始化界面如下:

在这里插入图片描述
1.初始化为U盘模式之后我们就可以使用光盘反复读写文件了,但每次读写都会消耗有限的磁盘读写空间。
2.初始化为用于CD/DVD播放机模式的时候,就只可以写入一次了,再次写入会将磁盘损坏。

DVD+R采用了一种称为Incremental Sequential Recording(增量顺序写入)写入方式,该方式不允许在会话关闭后继续写入。在DVD+R上创建一个会话后,一旦会话被关闭(Finalized),就不能再向该会话中追加写入新的数据。

windows调用

Windows操作光驱需要使用IMAPI(Image Mastering API)
IMAPI是一个用于创建和写入光盘映像文件的Windows API。它可以用于将文件和文件夹内容写入光盘,并创建可引导光盘。

1.创建映像对象

// 初始化 COM
CoInitializeEx(NULL, COINIT_MULTITHREADED); 

IDiscMaster* pDiscMaster = NULL;
HRESULT hr = CoCreateInstance(__uuidof(MsftDiscMaster2), NULL, CLSCTX_INPROC_SERVER, __uuidof(IDiscMaster2), (void**)&pDiscMaster);  

if (SUCCEEDED(hr)) {
    
    
    // 成功创建 
} else {
    
    
    // 创建失败
}

2.获取光驱数量和ID

IDiscMaster* pDiscMaster = NULL;
long totalDevices = 0; //光驱数量
HRESULT hr = CoCreateInstance(__uuidof(MsftDiscMaster2), NULL, CLSCTX_INPROC_SERVER, __uuidof(IDiscMaster2), (void**)&pDiscMaster);  
hr = m_discMaster->get_Count(&totalDevices);   
BSTR	uniqueID = NULL;  //光驱的ID
hr = m_discMaster->get_Item(0, &uniqueID);  

3.初始化刻录类

IDiscRecorder2* discRecorder = NULL;
BSTR recordUniqueId;
SAFEARRAY* m_volumePathNames;
HRESULT hr = CoCreateInstance(__uuidof(MsftDiscRecorder2), NULL, CLSCTX_INPROC_SERVER, __uuidof(IDiscRecorder2), (void**)&discRecorder);  
if (FAILED(hr)) return false;

//初始化刻录类
discRecorder->InitializeDiscRecorder(recordUniqueId);

//获取卷    
discRecorder->get_VolumePathNames(&m_volumePathNames);  

参考项目

Linux调用

Linux平台下用到的C++库:

1.libburn
libburn 是一个用于写入光盘的库,它支持 CD、DVD 和 Blu-ray。它提供了 C 接口,可以在 C++ 中使用。libburn 允许你创建数据和音频光盘,并提供了对光驱的低级别访问。
https://dev.lovelyhq.com/libburnia/libburn

sudo apt-get install libburn-dev

2.libcdio
libcdio 提供了一种接口,用于访问 CD-ROM 和 DVD-ROM 设备。它包括一组 C 函数,允许你读取光盘的数据、音轨等信息。libcdio 还包含用于访问 ISO-9660 文件系统的功能。
https://www.gnu.org/software/libcdio/

sudo apt-get install libcdio-dev  

3.libudev
libudev 是一个用于管理设备的库,你可以使用它来检测和获取有关设备的信息,包括 USB 光驱。你可以通过监听 udev 事件来获取插拔 USB 设备的通知。

sudo apt-get update  
sudo apt-get install libudev-dev  

读取设备驱动列表

1.使用libburn库读设备列表
使用libburn库读取USB光驱设备时异常,无法读取USB光驱。

参考项目

#include <iostream>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "libburn/libburn.h"

using namespace burn;
using namespace std;

int main(int argc, char const *argv[])
{
    
    
    struct burn_drive_info *drive_list;
    unsigned int drive_count = 0;
    int ret;
    //初始化libburn 
    if (!burn_initialize()){
    
    
	    cout << "init libburn failed" << endl;
	}
  
    //获取光驱的数量
    while(!burn_drive_scan(&drive_list, &drive_count));
        usleep(100002);

    if(drive_count <=0)
    {
    
    
        cout << "error to scan drive" << endl;
        return -1;
    }
    
    //抓取光驱
    ret = burn_drive_grab(drive_list[0].drive, 1);
    if(!ret)
    {
    
    
        cout << "error to grab the drive";
        return -1;
    }

    //释放光驱
    burn_drive_release(drive_list[0].drive, 1);
    //结束
    burn_finish();
    return 0;
}

2.使用liudev获取设备列表

#include <iostream>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <string>
#include <vector>
#include <libudev.h>
#include <linux/cdrom.h>
#include <fcntl.h>
#include <sys/ioctl.h>
/**
 * 获取所有光驱的列表
 */
std::vector<std::string> GetOpticalDriveList()
{
    
    
	udev* udev_context = udev_new();
	if (!udev_context)
		return {
    
    };

	std::vector<std::string> drives;
	udev_enumerate* enumerate = udev_enumerate_new(udev_context);
	if (enumerate)
	{
    
    
		udev_enumerate_add_match_subsystem(enumerate, "block");
		udev_enumerate_add_match_property(enumerate, "ID_CDROM_DVD", "1");
		udev_enumerate_scan_devices(enumerate);
		udev_list_entry* devices = udev_enumerate_get_list_entry(enumerate);

		udev_list_entry* dev_list_entry;
		udev_list_entry_foreach(dev_list_entry, devices)
		{
    
    
			const char* path = udev_list_entry_get_name(dev_list_entry);
			udev_device* device = udev_device_new_from_syspath(udev_context, path);
			const char* devnode = udev_device_get_devnode(device);
			if (devnode)
				drives.push_back(devnode);
			udev_device_unref(device);
		}
		udev_enumerate_unref(enumerate);
	}
	udev_unref(udev_context);

	return drives;
}

/**
 * 检查光驱是否可用
 */
bool GetValidDrive(std::string& drive)
{
    
    
	if (!drive.empty())
	{
    
    
		int fd = open(drive.c_str(), O_RDONLY | O_NONBLOCK);
		if (fd != -1)
		{
    
    
			if (ioctl(fd, CDROM_GET_CAPABILITY, 0) == -1){
    
    
               close(fd);
               return false;     
            }
			close(fd);
            return true;
		}
		else
		{
    
    
            return false;
		}
	}else{
    
    
        return false;
    }
}

3.使用libcdio库获取光驱数量

#include <cdio/cdio.h>
#include <cdio/cd_types.h>
#include <cdio/logging.h>

//打印日志
static void  log_handler(cdio_log_level_t level, const char message[])
{
    
    
  switch(level) {
    
    
  case CDIO_LOG_DEBUG:
  case CDIO_LOG_INFO:
    return;
  default:
    printf("cdio %d message: %s\n", level, message);
  }
}

int main(int argc, const char *argv[])
{
    
    
  char **ppsz_cd_drives=NULL, **c;
  
  //设置日志的回调函数
  cdio_log_set_handler(log_handler);

  //打印设备的CD驱动
  ppsz_cd_drives = cdio_get_devices(DRIVER_DEVICE);
  if (NULL != ppsz_cd_drives) 
    for( c = ppsz_cd_drives; *c != NULL; c++ ) {
    
    
      printf("-- Drive:  %s\n", *c);
    }

  //释放CD驱动
  cdio_free_device_list(ppsz_cd_drives);
  ppsz_cd_drives = NULL;
  printf("-----\n");
  return 0;
}

向光驱中写文件

通过命令行向光驱中写文件

# -Z 向选中的设备中烧入一个初始的session  
# -M 添加一个新的Session, 选项来避免关闭会话,从而在后续操作中保持会话打开
# -dvd-compat 提供对DVD-ROM的最大兼容性  
# -speed=N 指定光驱的刻录速度  
# -R: 用于支持 UNIX 文件系统的长文件名和权限
# -J: 用于支持 Windows 文件系统的长文件名。

# 初始化写入
growisofs -Z /dev/sr1 -R -J /home/users/file1 /home/users/file2  
# 追加写入  
growisofs -M /dev/sr1 -R -J /home/users/file3  

通过libburn命令写入文件

#include <iostream>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include "libburn/libburn.h"

using namespace burn;
using namespace std;

void burn_iso_to_disc(struct burn_drive *drive, char *iso_path)
{
    
    
    struct burn_source *data_src = NULL, *fifo_src = NULL;
    struct burn_disc *target_disc = NULL;
    struct burn_session *session = NULL;
    struct burn_write_opts *burn_options = NULL;
    enum burn_disc_status disc_state;
    struct burn_track *track;
    struct burn_progress progress;
    int fd = 0;
    off_t fixed_size;
    int fifo_chunksize = 2048;
    int fifo_chunks = 2048;
    int padding = 300 * 1024; //a padding of 300 kiB helps to avoid the read-ahead bug
    char reasons[BURN_REASONS_LEN];
    struct stat stbuf;
    time_t start_time;

    target_disc = burn_disc_create();
    session = burn_session_create();
    burn_disc_add_session(target_disc, session, BURN_POS_END);

    track = burn_track_create();
    burn_track_define_data(track, 0, padding, 1, BURN_MODE1);

    //打开需要写入的数据
    fd = open(iso_path, O_RDONLY);
    if (fd >= 0)
        if (fstat(fd, &stbuf) != -1)
            if ((stbuf.st_mode & S_IFMT) == S_IFREG)
                fixed_size = stbuf.st_size;
            else
            {
    
    
                cout << "error to open  filedescriptor\n"
                     << endl;
                return;
            }

    //转换文件为可写入的文件对象
    data_src = burn_fd_source_new(fd, -1, fixed_size);
    if (data_src == NULL)
    {
    
    
        cout << "Could not open data source " << iso_path << endl;
        return;
    }

    //安装fifo对象到数据源对象中
    fifo_src = burn_fifo_source_new(data_src, fifo_chunksize, fifo_chunks, 0);
    if (fifo_src == NULL)
    {
    
    
        cout << "Could not create fifo object of 4 MB\n"
             << iso_path << endl;
        return;
    }
    if (burn_track_set_source(track, fifo_src) != BURN_SOURCE_OK)
    {
    
    
        cout << "Cannot attach source object to track object\n";
        return;
    }

    burn_session_add_track(session, track, BURN_POS_END);

    burn_source_free(data_src);

    //检测驱动的状态
    disc_state = burn_disc_get_status(drive);
    if (disc_state != BURN_DISC_BLANK && disc_state != BURN_DISC_APPENDABLE)
    {
    
    
        return;
    }

    //创建烧写配置
    burn_options = burn_write_opts_new(drive);
    burn_write_opts_set_perform_opc(burn_options, 0); 
    burn_write_opts_set_multi(burn_options, 0);
    burn_write_opts_set_simulate(burn_options, 0);
    burn_write_opts_set_underrun_proof(burn_options, 1);
    if (burn_write_opts_auto_write_type(burn_options, target_disc, reasons, 0) == BURN_WRITE_NONE)
    {
    
    
        cout << "FATAL: Failed to find a suitable write mode with this media.\n"
             << "Reasons given:" << endl
             << reasons << endl;
        return;
    }
    burn_drive_set_speed(drive, 0, 0);

    burn_set_signal_handling((void*)"libburner : ", NULL, 0x30);

    cout << "Burning starts. With e.g. 4x media expect up to a minute of zero progress.\n";
   
    burn_disc_write(burn_options, target_disc);

    while (burn_drive_get_status(drive, NULL) == BURN_DRIVE_SPAWNING)
		usleep(100002);
    while (burn_drive_get_status(drive, &progress) != BURN_DRIVE_IDLE)
    {
    
    
        int size, free_bytes, ret;
        char *status_text;

        ret = burn_fifo_inquire_status(fifo_src, &size, &free_bytes, &status_text);
        if(ret > 0)
            cout << "fifo " << status_text << " %% " << 100 - (100.0*free_bytes/size) << " fill" << endl;

        sleep(1);
    }

    //释放缓存
    burn_write_opts_free(burn_options);
    burn_source_free(fifo_src);
    burn_track_free(track);
    burn_disc_free(target_disc);
}

int main(int argc, char const *argv[])
{
    
    
    struct burn_drive_info *drive_list;
    unsigned int drive_count = 0;
    int ret;

    //初始化
    if (!burn_initialize()){
    
    
        cout << "init burn drive failed" << endl;
		return -1;
	}

    //检测光驱
    while(!burn_drive_scan(&drive_list, &drive_count));
        usleep(100002);
    if(drive_count <=0)
    {
    
    
        cout << "error to scan drive" << endl;
        return -1;
    }

    //捕获光驱
    ret = burn_drive_grab(drive_list[0].drive, 1);
    if(!ret)
    {
    
    
        cout << "error to grab the drive";
        return -1;
    }

    //写文件
    burn_iso_to_disc(drive_list[0].drive, "myiso.iso");

    //释放光驱
    burn_drive_release(drive_list[0].drive, 1);
    burn_finish();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/yang1fei2/article/details/135277072
今日推荐