我想将文本写入文件。文本长度未知。所以我不知道要设置要使用的映射内存的大小,我将它设置为100。然后,问题出现了!字符串写入成功,但是剩余的100字节空间被NULL填充!!我怎样才能避免它???
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <windows.h>
#include <assert.h>
void main()
{
HANDLE hFile2 = CreateFile("hi.txt", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
assert(hFile2 != INVALID_HANDLE_VALUE);
// mapping..
HANDLE hMapping2 = CreateFileMapping(hFile2, NULL, PAGE_READWRITE, 0, 100, NULL);
assert(hMapping2 != NULL);
void* p2;
p2 = MapViewOfFile(hMapping2, FILE_MAP_WRITE, 0, 0, 0);
assert(p2 != NULL);
char *chp;
if(rand() % 2)
chp = "yeah!!";
else
chp = "good";
// copy
memcpy(p2, chp, strlen(chp));
// close
UnmapViewOfFile(p2);
CloseHandle(hMapping2);
CloseHandle(hFile2);
}