I study working with files. When writing the word "New word" everything seems to be fine. But in the output before the "new word" comes a line of one Chinese character. What can it be and how to win it.

HANDLE hFile; TCHAR slovo[] = _T("Новое слово"), P[30]; hFile = CreateFile(_T("proba2.zzz"), GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); DWORD HH; WriteFile(hFile, slovo, sizeof(slovo), &HH, NULL); ReadFile(hFile, P, sizeof(P), &HH, NULL); MessageBox(NULL, P, _T("Win32 Guided Tour"), NULL); CloseHandle(hFile); 
  • By chance, is this a BOM ? - karmadro4

1 answer 1

With your buffer P , no operation is performed at all, because there are 3 gross errors in the code .

  • You casually read the description of the CreateFile function . In the case of the CREATE_NEW parameter, an CREATE_NEW will be returned if the file already exists (that is, after the first launch of the program, your program stops doing anything at all) .

The correct parameter for your case is OPEN_ALWAYS .

  • In case you want to read and write at the same time, you must set the dwDesiredAccess parameter dwDesiredAccess the CreateFile function in GENERIC_READ | GENERIC_WRITE GENERIC_READ | GENERIC_WRITE

  • You cannot write something using hFile , and then read it back without moving the file pointer

After calling WriteFile you must add the line SetFilePointer(hFile, 0, 0, FILE_BEGIN);

Corrected fragment of the program:

 hFile = CreateFile(_T("proba2.zzz"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); DWORD HH; WriteFile(hFile, slovo, sizeof(slovo), &HH, NULL); SetFilePointer(hFile, 0, 0, FILE_BEGIN); ReadFile(hFile, P, sizeof(P), &HH, NULL);