Home > Software engineering >  assembly store text into an external file
assembly store text into an external file

Time:10-21

How to write data into an external file on Linux?

For instance, if I start the code with .include "output.s" and want to write "1111 0000" into it, then how to do this.

CodePudding user response:

The best way to do file I/O is to use the libc. Envision how you would do it in C, then do the same thing in assembly. For example, in C you could do

int main() {
    ssize_t n;
    int fd;
    char buf[9] = "1111 0000";

    fd = creat("output.s", 0666);
    if (fd == -1) {
        perror("output.s");
        return (EXIT_FAILURE);
    }

    n = write(fd, buf, sizeof buf);
    if (n == -1) {
        perror("output.s");
        return (EXIT_FAILURE);
    }

    close(fd);

    return (EXIT_SUCCESS);
}

Next, translate the code step by step into assembly:

        .data
name:   .string "output.s"              # the file name
buf:    .ascii  "1111 0000"
buflen=         .-buf                   # the length of buf

        .text
        .globl  main
        .type   main, @function

main:   push    %rbx                    # free rbx and align stack

        lea     name(%rip), %rdi        # file name
        mov     $0666, %esi             # initial permissions
        call    creat                   # create the file
        cmp     $-1,            
  • Related