Easily write lines to a text file

Started by Vortex, October 25, 2026, 06:38:33 PM

Previous topic - Next topic

Vortex

Hello,

Simple functions to write lines to a text file :

.386
.model flat,stdcall
option casemap:none

GENERIC_WRITE equ 40000000h
CREATE_ALWAYS equ 2

CreateFileA PROTO :DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD
CreateFile equ <CreateFileA>

.code

OpenFileToWrite PROC fname:DWORD

    invoke  CreateFile,fname,GENERIC_WRITE,\
            0,0,CREATE_ALWAYS,0,0
    ret

OpenFileToWrite ENDP

END

.386
.model flat,stdcall
option casemap:none

lstrlenA PROTO :DWORD
lstrlen EQU <lstrlenA>

WriteFile PROTO :DWORD,:DWORD,:DWORD,:DWORD,:DWORD

.code

WriteLine PROC hFile:DWORD,LineAddr:DWORD

LOCAL BytesWritten:DWORD

    invoke  lstrlen,LineAddr
    lea     edx,BytesWritten
    invoke  WriteFile,hFile,LineAddr,eax,edx,0
    ret

WriteLine ENDP

END

A quick example :

.386
.model flat,stdcall
option casemap:none

CloseHandle PROTO :DWORD
ExitProcess PROTO :DWORD

OpenFileToWrite PROTO :DWORD
WriteLine PROTO :DWORD,:DWORD

.data

fname   db 'Test.txt',0
line1   db 'This is a test.',13,10,0
line2   db 'Another test.',0

.data?

hFile   dd ?

.code

start:

    invoke  OpenFileToWrite,ADDR fname
    mov     hFile,eax

    invoke  WriteLine,eax,ADDR line1
    invoke  WriteLine,hFile,ADDR line2

    invoke  CloseHandle,hFile

    invoke  ExitProcess,0

END start
Code it... That's all...

TimoVJL

Those support functions are also useful for x64, when parameter count is less that five.
May the source be with you

Vortex

Hi Timo,

Attached is the 64-bit version of the functions.
Code it... That's all...

Vortex

#3
Here is the example rewritten with Pelles C :

#define WIN32_LEAN_AND_MEAN
#include <stdio.h>
#include <windows.h>

extern HANDLE __stdcall OpenFileToWrite(char *file);
extern int __stdcall WriteLine(HANDLE h,char *TextLine);

int main(int argc,char *argv[])
{
    HANDLE hFile;
    char *line1="This is a test.\r\n";
    char *line2="Another test.";

    hFile=OpenFileToWrite("Test.txt");
    WriteLine(hFile,line1);
    WriteLine(hFile,line2);

    CloseHandle(hFile);
    return 0;
}
Code it... That's all...

Vortex

Another version :

include     OpenNewTxtForOutput.inc

.data

msg         db 'This is a test.',0
msg2        db 'Another test',0
file        db 'Test.txt',0

.data?

hFile       dd ?

.code

OpenNewTxtForOut PROC filename:DWORD

LOCAL mode:DWORD

    mov     mode,'w'
    invoke  fopen,filename,\
            ADDR mode
    ret

OpenNewTxtForOut ENDP

put PROC handle:DWORD,pMemory:DWORD
   
    invoke  lstrlen,pMemory
    invoke  fwrite,pMemory,1,\
            eax,handle
    ret

put ENDP

start:

    invoke  OpenNewTxtForOut,ADDR file
    mov     hFile,eax
   
    invoke  put,eax,ADDR msg
    invoke  put,hFile,ADDR msg2
    invoke  fclose,hFile
   
    invoke  ExitProcess,0

END start
Code it... That's all...