-1

This is the echo utility program. It reads the command-line argument from the console and prints it back to the console. In the following block of code, at line 10, why write a space to the console when there is not the end of argument string?

#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"

int main(int argc, char *argv[])
{
  int i;
  for(i = 1; i < argc; i++){
    write(1, argv[i], strlen(argv[i]));
    if(i + 1 < argc){
      write(1, " ", 1); //line 10
    } else {
      write(1, "\n", 1);
    }
  }
  exit(0);
}
Aries Zhao
  • 29
  • 6

1 Answers1

1
if(i + 1 < argc){
  write(1, " ", 1); //line 10
} else {
   write(1, "\n", 1);
}

This simply prints newline after the last argument only, otherwise it prints a space to separate adjacent arguments. In other words, output is arguments in the single line, separated by spaces, ending the line with newline.

hyde
  • 60,639
  • 21
  • 115
  • 176
  • I have run it, it prints out without the space. I assume the result should be `s t a c k` after `echo stack` command. But actually the printed result is `stack`. That is why I wonder about line 10. Still thank you anyway~ – Aries Zhao Jul 03 '22 at 07:25
  • @AriesZhao: `echo stack` has only one argument (or two if you count `argv[0]`, which is `"echo"`). Think about how you might have discovered that all by yourself, and how much better you would have learned about command line arguments. – rici Jul 03 '22 at 08:10
  • @rici Now that I totally gets it! Thank you so much for the tips. – Aries Zhao Jul 03 '22 at 08:24