title: tee command in C with option
body: <p>I have command tee in C, and I should add option -a which :supports the -a option file, which results in adding the data being read to the end of the file, if available.  Anyone could help?
   I try put inside :</p>
  
  <pre><code>if ( (option = getopt(argc,argv,"a")) != -1 ){
             switch (option){
             case 'a':
  </code></pre>
  
  <p>But I don't know what next.</p>
  
  <pre><code>main(int argc, char *argv[]){
  
  FILE *fp, *fp1;
  char buffer;
  
  if(argc != 4){
  printf("\nError");
  printf("\nSintaxis: tee [archivo1] [archivo2]\n");
  exit(0);
  }
  
  if(strcmp(argv[1], "tee") == 0){
  fp = fopen(argv[2], "r");
  fp1 = fopen(argv[3], "w");
  
  printf("\Content in %s:\n", argv[2]);
  
  while(!feof(fp)){
      buffer = fgetc(fp);
      fputc(buffer, fp1);
      printf("%c", buffer);
  }
  
  printf("\n\n%s received %s\n", argv[3], argv[2]);   
  
  fclose(fp);
  fclose(fp1);
  }
  else
      printf("\nThe first argument have to be tee\n");
  }
  </code></pre>
  
  <p>Second version , I think better.
   But if I run program without option -a else if (argc == 2) {
        printf("Write to file: %s\n", argv[1]);
        process_save_reading(argv[1],"w+") write some text in file argv[1] -file is empty</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;unistd.h&gt;
  
  
  void usage() {
  fprintf(stderr, "Usage: [-a program]");
  exit(1);
  }
  
  void err(char * s1, char * s2) {
  fprintf(stderr, "Error: %s ", s1);
  perror(s2);
  exit(1);
  }
  void process_reading() {
  int c = fgetc(stdin);
  while (c != EOF) {
  putchar(c);
  c = getchar();
  }
  }
  
  void write_file_content(char * filename, int cnt, const char* mode) {
  FILE *fp;
  if ((fp = fopen(filename, mode)) == NULL) {
  fprintf(stderr, "Can not open file: %s\n", filename);
  exit(1);
  }
  fputc(cnt, fp);
  fclose (fp);
  }
  
  void process_save_reading(char * filename, const char* mode) {
  int c = fgetc(stdin);
  while (c != EOF) {
  putchar(c);
  write_file_content(filename, c, mode);
  c = getchar();
  }
  }
  
  int file_exists(char * filename) {
  return access(filename, F_OK) != -1;
  }
  int main(int argc, char * argv[]) {
  char * opts = "a:";
  int c;
  
  if (argc == 1) {
  process_reading();
  }
  else if (argc == 2) {
  printf("Write to file: %s\n", argv[1]);
  process_save_reading(argv[1],"w+");
  } 
  else {
  while ((c = getopt(argc, argv, opts)) != -1) {
      switch (c) {
          case 'a':
              if (!file_exists(optarg)) {
                  fprintf(stderr, "File: '%s' doesn't exists\n", optarg);
                  exit(1);
              }
              printf("Save to file: %s\n", optarg);
              process_save_reading(optarg,"a+");
  </code></pre>