The MASM Forum Archive 2004 to 2012

General Forums => The Campus => Topic started by: mathewzhao on September 18, 2008, 02:25:44 AM

Title: A program in trouble about memory-mapped files
Post by: mathewzhao on September 18, 2008, 02:25:44 AM
I recently learned  memory-mapped files,so I programmed a program in order to deeply understand it,but some question always puzzle me.

Intention:
  I create a null text file,then the program writes the string "Hello,World!" into the text file.

Step:
  1)create a null text file at C:\MappingFile.txt
  2)input the following source code(the code is really easy),and executes it.

Q:
1: After the program run,the null text file is still a null file.The string doesn't be written into the file.
2: If I input 2 letters into the file before the program run ,I will see 'He' in the file after the program run.

.386
.Model Flat, StdCall
Option Casemap :None

include    windows.inc
include    kernel32.inc
includeLib kernel32.lib

ModifyFile PROTO  :DWORD

.data
MyFile     db 'C:\MappingFile.txt',0     
Msg        db 'Hello,World!',0         

.data?
hFile      dd  ?
hMap       dd  ?
pMapAddr   dd  ?

.code

ModifyFile proc uses ebx esi edi,lpBufferAddress:DWORD
    mov edi,lpBufferAddress     
    invoke lstrcpy,edi,addr Msg 
    ret
ModifyFile endp

START:
invoke CreateFile,ADDR MyFile,GENERIC_READ or GENERIC_WRITE,NULL, NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL, NULL                 
   
.if eax!=INVALID_HANDLE_VALUE         
mov hFile, eax               
invoke CreateFileMapping, hFile,NULL,PAGE_READWRITE,0,0,NULL
.if eax!=NULL   
                mov hMap,eax             
invoke MapViewOfFile,hMap,FILE_MAP_WRITE,0,0,NULL
.if eax!=NULL
mov pMapAddr,eax                 
invoke ModifyFile,pMapAddr     
invoke UnmapViewOfFile,pMapAddr
.endif
invoke CloseHandle,hMap       
.endif
invoke CloseHandle, hFile         
.endif
    invoke ExitProcess,0                   
END START     

Title: Re: A program in trouble about memory-mapped files
Post by: bozo on September 18, 2008, 03:02:43 AM
i haven't run the code, but since on error no message will be displayed, how are you sure anything is written to the file?
are you stepping through the code with a debugger?

Try using FlushViewOfFile (http://msdn.microsoft.com/en-us/library/aa366563(VS.85).aspx) which is same as fflush() in C
Title: Re: A program in trouble about memory-mapped files
Post by: zooba on September 18, 2008, 05:26:52 AM
If you don't specify the size of the file in CreateFileMapping, it will default to the current size.

Try this:

invoke CreateFileMapping, hFile,NULL,PAGE_READWRITE,0,256,NULL

(Keeping in mind that the extended space may contain garbage.)

Cheers,

Zooba :U
Title: Re: A program in trouble about memory-mapped files
Post by: BogdanOntanu on September 18, 2008, 06:49:10 AM
And why mapping the file when you could simply WRITE the message text to the file?

Is this some kind of homework?