I've recently read this article on using printf and scanf in assembly:
Meaning of intfmt: db "%d", 10, 0 in assembly
In particular it says "In printf, the newline prints a newline and then (if the output is in line buffered mode, which it probably is), flushes the internal output buffer so you can actually see the result. So when you remove the 10, there's no flush and you don't see the output."
However I do not know what to do if I do not want a newline after my output in my assembly file. Here's a simple test file I've written to try printing without a newline:
extern printf
LINUX        equ     80H      ; interupt number for entering Linux kernel
EXIT         equ     60       ; Linux system call 1 i.e. exit ()
section .data
    int_output_format: db "%ld", 0
segment .text
    global  main
main:
    mov r8, 10
    push rdi
    push rsi
    push r10
    push r9
    mov rsi, r8
    mov rdi, int_output_format
    xor rax, rax
    call printf
    pop r9
    pop r10
    pop rsi
    pop rdi
    call os_return      ; return to operating system
os_return:
    mov  rax, EXIT      ; Linux system call 1 i.e. exit ()
    mov  rdi, 0     ; Error code 0 i.e. no errors
    syscall     ; Interrupt Linux kernel 64-bit
but as the article I've read suggests stdout isn't being flushed. I was thinking perhaps I need to somehow flush after I output the number? But I'm really not sure.
I am using the NASM assembly language.
Thanks in advance!
The printf statement does not automatically append a newline to its output. It outputs only what the format string specifies. So if a newline is needed, you must include one in the format string.
To clarify the title of the question: printf(..) does not do any flushing itself, it's the buffering of stdout that may flush when seeing a newline (if it's line-buffered).
The escape sequence \n means newline. When a newline appears in the string output by a printf, the newline causes the cursor to position to the beginning of the next line on the screen.
fflush() flushes buffered output in line or full-buffered stdio streams:
extern fflush
...
xor  edi, edi          ; RDI = 0
call fflush            ; fflush(NULL) flushes all streams
...
Alternatively, mov rdi, [stdout] / call fflush also works to flush only that stream.  (Use default rel for efficient RIP-relative addressing, and you'll need extern stdout as well.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With