使用writefile编写原始usb c++

use writefile to write raw usb c++

本文关键字:usb c++ 原始 writefile 使用      更新时间:2023-10-16

这是我的代码:

#include <string.h>
#include <malloc.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <Windows.h>
#include <stdio.h>
#include <iostream> 
int main(int argc, CHAR* argv[]) {
PVOID data[1024];
DWORD dwBytesRead = 0;
DWORD dwBytesWrite = 512;
HANDLE hFile = CreateFile(L"\\.\E:", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
if (hFile == INVALID_HANDLE_VALUE) {
    printf("Error %x", GetLastError());
    return 1;
}
PVOID ToBe = "hello world from usb";
if (WriteFile(hFile,&ToBe,512,&dwBytesWrite,    NULL) == 0)
{
    printf("writeFile error: %x", GetLastError());
    return 1;
}
while (ReadFile(hFile, &data, 512, &dwBytesRead, NULL) != 0) {
    printf("%s", data);
}
if (ReadFile(hFile, &data, 512, &dwBytesRead, NULL) == 0) {
    printf("ReadFile error: %x", GetLastError());
    return 1;
}
return 0;
}

现在它看起来像在工作,但我看不到USB中的"你好世界"。。。我做错了什么?

(p.s.在我运行程序后,如果不格式化他,我就无法再次打开USB,所以确实写了一些东西,但在那之后,我无法用径向函数看到它…)

您写入512个字节,这将使文件指针前进512个字节。然后你从这一点开始阅读。相反,您需要将文件指针找回到开头。使用SetFilePointerEx执行此操作。