4

我想将文本写入文件。文本长度未知。所以我不知道要设置要使用的映射内存的大小,我将它设置为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);
}
4

1 回答 1

3

该函数SetEndOfFile会将物理文件大小设置为文件指针的当前位置。并将SetFilePointer设置文件指针。

所以要截断文件:

   CloseHandle(hMapping2); // do first
   SetFilePointer(hFile2, strlen(chp), 0, 0);
   SetEndOfFile(hFile2); 
于 2015-01-02T17:56:42.827 回答