如何将DWORD或字符串转换为BYTE *

时间:2019-09-20 07:01:13

标签: c++ file winapi

您好,我正在创建文件加密代码,我读取了一个文件,并且需要将正在读取的文件转为BYTE *,但每次尝试获取"CL.exit"时,我都尝试进行搜索。这就是我读取文件的方式。

HANDLE getFile = createFile();
    DWORD reciveBytes = 0;
    //If it's byte or kilobyte the size of the buffer will be 1024.
    //If it's megabytes or gigabyte the size of the buffer will be 4096.
    const DWORD Buffersize = 66232; // gave me warning for 1024
    DWORD buffer[Buffersize];
    string fileInput;
    if (ReadFile(
        getFile,
        buffer,
        Buffersize,
        &reciveBytes,
        NULL
    )) {
    }
    else {
        cout << "Faild!" << endl;
        cout << GetLastError() << endl;
    }
    /*
    for (unsigned int i = 0; i < reciveBytes; i++) {
        if (buffer[i] != '\0') {
            fileInput = fileInput + buffer[i];
        }
    }
    */
    return buffer[reciveBytes];

现在,我需要做的是将返回类型设置为BYTE *,这样我可以执行以下操作:BYTE* protect = (BYTE*)"Hello world!"; 这是createFile():

HANDLE getFile = CreateFileA(
        fileName,
        GENERIC_READ,
        0,
        NULL,
        OPEN_ALWAYS,
        FILE_ATTRIBUTE_NORMAL, 
        NULL
    );

1 个答案:

答案 0 :(得分:1)

#include <windows.h>
#include <iostream>
HANDLE createFile()
{
    HANDLE getFile = CreateFileA(
        "xxx.txt",
        GENERIC_READ,
        0,
        NULL,
        OPEN_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);
        return getFile;
}
BYTE* memoryfromfile()
{
    HANDLE getFile = createFile();
    DWORD reciveBytes = 0;
    //If it's byte or kilobyte the size of the buffer will be 1024.
    //If it's megabytes or gigabyte the size of the buffer will be 4096.
    const DWORD Buffersize = 66232; // gave me warning for 1024
    BYTE* memory = new BYTE[Buffersize];
    memset(memory, 0, Buffersize);
    std::string fileInput;
    if (ReadFile(
        getFile,
        memory,
        Buffersize,
        &reciveBytes,
        NULL
    )) {
    }
    else {
        std::cout << GetLastError() << std::endl;
        std::cout << "Faild!" << std::endl;
    }
    /*
    for (unsigned int i = 0; i < reciveBytes; i++) {
        if (buffer[i] != '\0') {
            fileInput = fileInput + buffer[i];
        }
    }
    */
    return memory;
}
int main()
{
    BYTE * temp = memoryfromfile();
    std::cout << "temp = " << temp << std::endl;
    delete temp;
    system("pause");
    return 0;
}