CreateFileMapping() 用于将长度未知的文本写入文件

CreateFileMapping() for writing text whose length is unknown to file

我想将文本写入文件。文本长度未知。所以想不出设置要使用的mapped memory的大小,就设置为100。然后,问题出现了!字符串写入成功,但是剩下的space100字节被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);
}

函数SetEndOfFile will set the physical file size to the current position of the file pointer. And SetFilePointer将设置文件指针。

因此要截断文件:

   CloseHandle(hMapping2); // do first
   SetFilePointer(hFile2, strlen(chp), 0, 0);
   SetEndOfFile(hFile2);