I'm trying to write a sequence of random numbers to a file called filedemo.dat, here's a snippet of code I have:
.data
filenametemp db "filedemo.dat",0
...
...
.if (PAINT_RANDNUM>0)
invoke TextOut,hdc,200,150,pBuffer,len(pBuffer)
invoke CreateFile,ADDR filenametemp,GENERIC_READ+GENERIC_WRITE,FILE_SHARE_READ+FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_ARCHIVE,NULL
mov hFile,eax
invoke SetFilePointer,hFile,NULL,NULL,FILE_END
invoke WriteFile,hFile,pBuffer,len(pBuffer),NULL,NULL
invoke CloseHandle,hFile
mov PAINT_RANDNUM,0
.endif
On my desktop running Windows 8, it creates the file and writes to it all the random numbers it prints on the screen until I close the program.
On my laptop running Windows 7, it creates the file, writes one random number, then crashes. It doesn't even print the number on the screen. But if I comment out the block of code that's doing file I/O, it prints out the numbers onscreen no problem.
Any ideas? Thanks for any info!
First suggestion is there is no reason to endlessly open then close the file, it makes the task very slow. Open the file once, use WriteFile for each random number, you may also need to send some form of separator to keep the numbers apart (Comma, CRLF etc ....) and if you are writing the numbers sequentially (1 after the other) you don't need to keep setting the file pointer after each write as it is incremented after each write.
Wow thanks for the quick response! I looked up the WriteFile function and it looks like I shouldn't make the lpNumberOfBytesWritten field NULL if lpOverlapped is NULL as well. Don't know why it runs fine under Windows 8 though. I made the following change and it runs fine now under Windows 7:
.data
filenametemp db "filedemo.dat",0
SpaceChar db " ",0
.data?
SzRdWr DWORD ?
...
...
invoke CreateFile,ADDR filenametemp,GENERIC_READ+GENERIC_WRITE,FILE_SHARE_READ+FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_ARCHIVE,NULL
mov hFile,eax
invoke SetFilePointer,hFile,NULL,NULL,FILE_END
invoke WriteFile,hFile,pBuffer,len(pBuffer),ADDR SzRdWr,NULL
invoke WriteFile,hFile,ADDR SpaceChar,1,ADDR SzRdWr,NULL
invoke CloseHandle,hFile
I was going to take your advice and relocate the CloseHandle function elsewhere but caught a note in the WriteFile function saying:
When writing to a file, the last write time is not fully updated until all handles used for writing have been closed. Therefore, to ensure an accurate last write time, close the file handle immediately after writing to the file.
Is that something to be concerned about?
Thanks again for the help!
The basic mechanics is you open or create the file first, save the file handle once as a GLOBAL in your DATA? section, then each time you need to add a number, call WriteFile(). When you have finished writing to the file, then call CloseHandle(). When you close the file it will have the current file time and date. Opening and closing the file each write is very slow and inefficient.
you really don't care about the file time