title: read and write to file assembly
body: <p>I have an inputfile.txt which looks like this: <code>3 4 2 0 8 1 5 3</code></p>
  
  <p>I'm trying to write inside an <code>outputfile.txt</code> each character of inputfile incremented by 1. 
  So inside outputfile.txt I should see <code>4 5 3 1 9 2 6 4</code>.
  I have tried to write this piece of code but I have several doubts.</p>
  
  <pre><code>.section .data
    buff_size: .long 18
  
  .section .bss
    .lcomm buff, 18
  
  .section  .text              # declaring our .text segment
    .globl _start              # telling where program execution should start
  
  _start:
  
      popl %eax       # Get the number of arguments
      popl %ebx       # Get the program name
      popl %ebx       # Get the first actual argument - file to read
  
      # open the file
      movl $5, %eax       # open 
      movl $0, %ecx       # read-only mode
      int $0x80        
  
      # read the file
  
      movl $0, %esi
      movl %eax, %ebx     # file_descriptor
  
      analyzecharacter:   #here I want to read a single character
          movl $3, %eax       
          movl $buff, %edi    
          leal (%esi,%edi,1), %ecx    
          movl $1, %edx
          int $0x80
          add $1, %esi #this point is not clear to me, what I'd like to do is to increment the index of the buffer in order to be positioned on the next cell of buffer array, I've added 1 but I think is not correct
          cmp $8, %esi  # if I've read all 8 characters then I'll exit
          je exit
  
      openoutputfile:
      popl %ebx       # Get the second actual argument - file to write
      movl $5, %eax       # open
      movl $2, %ecx       # read-only mode
      int $0x80       
  
      writeinoutputfile:
      #increment by 1 and write the character to STDOUT
      movl %eax, %ebx     # file_descriptor
      movl $4, %eax       
      leal (%esi,%edi,1), %ecx
      add $1, %ecx #increment by 1        
      movl $1, %edx   
      int $0x80
      jmp analyzecharacter        
  
      exit:
      movl $1, %eax       
      movl $0, %ebx       
      int $0x80   
  </code></pre>
  
  <p>I have 2 problems/doubts:</p>
  
  <p>1- my first doubt is about this instruction: <code>add $1, %esi</code>. Is this the right way to move through <code>buffer</code> array? </p>
  
  <p>2- The second doubt is: When I analyze each character should I always invoke <code>openoutputfile</code> label? I think that in this way I'm reopening the file and the previous content is overwritten.
  Indeed if I run the program I see only a single character <code>\00</code> (a garbage  character, caused by the value of %esi in this instruction I guess: <code>leal (%esi,%edi,1), %ecx</code> ).</p>
  
  <p>I hope my problems are clear, I'm pretty new to assembly and I've spent several hours on this.</p>
  
  <pre><code>FYI: 
  I'm using GAS Compiler and the syntax is AT&amp;T.
  Moreover I'm on Ubuntu 64 bit and Intel CPU. 
  </code></pre>