-2

this is my code :

#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;
}

Now it looks like working, but I can't see the "hello world" in the USB... what I did wrong?

(p.s. after I run the program I can't open my USB again without formating him, so something indeed got written, but I can't see it with the radial function right after that...)

FFF GGG
  • 1
  • 1

1 Answers1

2

You write 512 bytes, and that advances the file pointer by 512 bytes. You then read from that point. Instead you need to seek the file pointer back to the beginning. Use SetFilePointerEx to do that.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490