4

I want to write text to file. The length of text is unknown. So I have no idea to set the size of mapped memory to be used, and I set it to 100. Then, problem appears! the string is written successfully, but the rest space of 100 bytes is filled with NULL!! How can I avoid it???

#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