from Hacker News

Write assembly that opens each file in a dir and changes foo with bar

by frogger8 on 1/4/23, 2:37 AM with 1 comments

Write an assembly program that opens each file in a directory and then changes all of the occurences of foo with bar.

;Open a file handle

mov ax, 3Dh

mov dx, offset filename

int 21h

;Check that the file handle is valid

cmp ax, 0

jne file_open

;Start looping through the directory

mov si, offset directory

mov di, offset filename

loop:

mov al, [si]

cmp al, 0

je exit

;Copy the filename

mov [di], al

inc si

inc di

jmp loop

file_open:

;Read the file and search for "foo"

mov bx, ax

mov ah, 3Fh

mov cx, 0FFFFh

mov dx, offset buffer

int 21h

;Check if the end of file has been reached

cmp ax, 0

je exit

;Loop through the read buffer

mov si, offset buffer

mov di, offset replace

loop2: mov al, [si] cmp al, 'f' je check_foo inc si jmp loop2

check_foo: cmp byte [si + 1], 'o' jne loop2 cmp byte [si + 2], 'o' jne loop2

;Replace "foo" with "bar" mov [di], 'b' inc di mov [di], 'a' inc di mov [di], 'r' inc di jmp loop2

;Write the modified buffer to the file mov bx, ax mov ah, 40h mov cx, 0FFFFh mov dx, offset replace int 21h

;Go to the next file jmp file_open

exit: ;Close the file mov ah, 3Eh int 21h

;Exit mov ax, 4C00h int 21h

  • by frogger8 on 1/4/23, 3:12 AM

    OP here, I asked… even chatGPT doesn’t know how to make the new lines format properly on HN :)