0

I am a complete beginner in MIPS and I am trying to understand a piece of code which is about opening a file , saving the file and then closing the file.

#open file
    li $v0, 13
        la $a0, fname       #file name 
        li $a1, 1           #flags: 1-write file
        li $a2, 0           #mode: ignored
        syscall
    move $s1, $v0      # save the file descriptor

#check for errors - if the file was opened
#...

#save file
    li $v0, 15
    move $a0, $s1
    la $a1, image
    li $a2, BMP_FILE_SIZE
    syscall

#close file
    li $v0, 16
    move $a0, $s1
        syscall

I understand everything except this 'saving the file descriptor part'. Can anybody explain what a file descriptor is and why we are using it here? The instructions that I don't understand :

  1. move $s1, $v0
  2. move $a0, $s1
  3. move $a0, $s1
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • http://courses.missouristate.edu/kenvollmar/mars/help/syscallhelp.html shows the calling convention for system calls. See https://en.wikipedia.org/wiki/File_descriptor - it's a number, a handle that the kernel (or the MARS simulator) returns from an `open` system call, that you can use to read/write that open file. – Peter Cordes May 06 '21 at 16:24
  • So when we open the file $v0 contains the file descriptor (a unique identifier for that file) so we save that value in $s1 using the (move $s1, $v0 ) instruction and then use that file descriptor later for saving that file and closing the file? –  May 06 '21 at 16:37
  • Yup, that's right. That's why `move $s1, $v0` has a comment that says "save the file descriptor". (The unique id isn't exactly "for that file", though, it's for that *open*. You could open the same file twice and have two different read/write positions active on different descriptors. Google more about file descriptors.) – Peter Cordes May 06 '21 at 16:40
  • But why is it necessary to store the file descriptor? –  May 06 '21 at 17:19
  • Because you need to overwrite `$v0` with the call-number for the next system call. The final `move $a0, $s1` *is* redundant because `write()` doesn't destroy its arg-passing registers, so `$a0` still holds the FD. – Peter Cordes May 06 '21 at 17:28
  • Copying to `$s1` instead of directly to `$a0` is also redundant. So if that's what you mean, then no you didn't need to "save" it in `$s1`, that's just inefficient coding in the example. Perhaps trying to be "simpler" or "more obvious". – Peter Cordes May 06 '21 at 17:30

0 Answers0