Search code examples
c++writefile

c++ adding text variables with WriteFile errors


my problem is that when I use this:

LPSTR a = "0";
LPSTR b = "1";
LPSTR c = "2";
LPSTR d = "3";
LPSTR e = "4";

TCHAR strex[5];
DWORD x;

myFile = CreateFile("C:\\a.txt", FILE_WRITE_DATA, NULL, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);

TCHAR n[5];
StringCchCopy(n, 5, a);
StringCchCat(n, 5, b);
StringCchCat(n, 5, c);
StringCchCat(n, 5, d);
StringCchCat(n, 5, e);

strex = n;

WriteFile(myFile, strex, (DWORD)(sizeof(strex)), &x, NULL);
CloseHandle(myFile);

I get this error for this line: strex = n; error C2106: '=' : left operand must be l-value

If I change TCHAR strex[5]; to TCHAR strex; then I get the following errors:

error C2440: '=' : cannot convert from 'TCHAR [5]' to 'TCHAR'

and

error C2664: 'WriteFile' : cannot convert parameter 2 from 'TCHAR' to 'LPCVOID'

Is there anyway to accomplish what I'm trying to do with different code? Help would be appreciated.


Solution

  • You must be using an old compiler as C2106 is the wrong error. It should be

    error C3863: array type 'TCHAR [5]' is not assignable

    When you:

    TCHAR strex[5];

    You are creating an array of five chars on the stack. strex is a pointer to that array. You can not change that pointer. So when you:

    strex = n;

    You are asking to assign the pointer n to the pointer strex. If you want a pointer to n then:

    TCHAR* strex= n;

    Will work. But you don't even have to do that, you already have the pointer with n!

    WriteFile(myFile, n, (DWORD)(sizeof(n)), &x, NULL);