如何使用c ++中的备份API进行备份

时间:2012-11-08 04:58:01

标签: c++ visual-c++ backup volume-shadow-service

我正在编写一个用于备份某些指定文件的应用程序,因此使用备份API调用,即 CreateFile BackupRead和WriteFile API

获取错误访问违规读取位置。

我在下面附上了代码。

#include <windows.h>

int main()
{
    HANDLE hInput, hOutput;

//m_filename is a variable holding the file path to read from
hInput = CreateFile(L"C:\\Key.txt", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);

//strLocation contains the path of the file I want to create.
hOutput= CreateFile(L"C:\\tmp\\", GENERIC_WRITE, NULL, NULL, CREATE_ALWAYS, NULL, NULL); 


DWORD dwBytesToRead = 1024 * 1024 * 10;
BYTE *buffer;
buffer = new BYTE[dwBytesToRead];
BOOL bReadSuccess = false,bWriteSuccess = false;
DWORD dwBytesRead,dwBytesWritten;
LPVOID lpContext;
//Now comes the important bit:

do
{
    bReadSuccess = BackupRead(hInput, buffer, sizeof(BYTE) *dwBytesToRead, &dwBytesRead, false, true, &lpContext);

    bWriteSuccess= WriteFile(hOutput, buffer, sizeof(BYTE) *dwBytesRead, &dwBytesWritten, NULL); 

}while(dwBytesRead == dwBytesToRead);

return 0;

}

任何人都建议我如何使用这些API?

感谢。

1 个答案:

答案 0 :(得分:0)

阅读文档。具体而言,BackupRead文档的第二段:

  

在第一次调用指定文件或目录的lpContext之前,必须将NULL指向的变量设置为BackupRead

您的代码也非常需要错误处理 - 您根本不会检查错误,而实际上许多API可能会失败(请查看每个API的文档以了解函数可能如何失败以及发生的情况当它失败时)。您还应该实现正确的资源处理,例如通过关闭文件句柄。