Question

I have code

   HANDLE file;

   file = CreateFile(L"D:\\SystemWin\\a.txt",
    GENERIC_READ | GENERIC_WRITE,
    0,
    NULL,
    CREATE_ALWAYS,
    FILE_ATTRIBUTE_NORMAL,
    0);

    if(file == INVALID_HANDLE_VALUE){
      wprintf(L"Invalid file handle\n");
      return 1;
    }

    wcsncpy(aBuffer, L"1234567890\0", BUF_SIZE);
    WriteFile(file, aBuffer, wcslen(aBuffer), &writtenByte, NULL); 

If I got it right in my file I shoud have text "1234567890" but I have 12345 instead. What cound be wrong? BUF_SIZE is 11

Was it helpful?

Solution

wcslen returns the number of wchar_t elements in aBuffer before a null terminator (in your case, this is 10).

But WriteFile wants the number of BYTES. You need to do this instead:

WriteFile(file, aBuffer, wcslen(aBuffer) * sizeof(wchar_t), &writtenByte, NULL); 

Also note that string literals are automatically null-terminated in C. So your string literal L"1234567890\0" is actually 12 characters long ("1234567890\0\0"). Rewrite it as just L"1234567890" instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top