Click here to Skip to main content
15,887,346 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more: , +
i want create a filemapping and modify my file,but when i modify my file ,but it not what i want,my english is very poor ,you can see this code
my project is unicode
<br />
hfile=::CreateFile(TEXT("c:\\1.txt"),GENERIC_ALL|FILE_ALL_ACCESS,FILE_SHARE_WRITE|\<br />
FILE_SHARE_READ,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);<br />
HANDLE hmap=::CreateFileMapping(hfile,NULL,PAGE_READWRITE,0,0,NULL);<br />
TCHAR*pmap=(TCHAR*)::MapViewOfFile(hmap,FILE_MAP_ALL_ACCESS,0,0,NULL);<br />
TCHAR*tmp=pmap;<br />
lstrcpy(tmp,TEXT("my test"));<br />
::UnmapViewOfFile(pmap);<br />
::CloseHandle(hmap);<br />
::CloseHandle(hfile);<br />

c:\1.txt is "m y t e s t" ,i want it is "my test"
how do i achieve this
Posted

1 solution

If you want to create UNICODE text files, you should add a BOM (byte order mark) at the begin of the file to instruct the operating system about the file encoding. If you don't do it, text files are always written on disk as ASCII; it doesn't matter if your code is compiled to use UNICODE.

In other words, the first time you create the text file, prior to any operation on it, you shouyld write two binary bytes on it: 0xFF and 0xFE. You can do it in the following way:

C++
hfile = ::CreateFile(
   TEXT("c:\\1.txt"),
   GENERIC_ALL | FILE_ALL_ACCESS,
   FILE_SHARE_WRITE | FILE_SHARE_READ,
   NULL,
   OPEN_ALWAYS,
   FILE_ATTRIBUTE_NORMAL,
   NULL);
HANDLE hmap = ::CreateFileMapping(
   hfile,
   NULL,
   PAGE_READWRITE,
   0,
   0,
   NULL);
TCHAR *pmap = (TCHAR*)::MapViewOfFile(
   hmap,
   FILE_MAP_ALL_ACCESS,
   0,
   0,
   NULL);
*pmap = (TCHAR)0xFEFF;
TCHAR *tmp = pmap + 1;
lstrcpy(tmp, TEXT("my test"));
::UnmapViewOfFile(pmap);
::CloseHandle(hmap);
::CloseHandle(hfile);


For more informations about BOM you can follow this link: http://www.websina.com/bugzero/kb/unicode-bom.html[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900