#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>

int main() {
  
  int fd;
  int n_read, m_written;
  char buf[50];  // buffer of 50 characters
  
  /* open file /tmp/foo for writting */

  fd = open("/tmp/foo",O_WRONLY | O_APPEND);
  
  /* check if open was successful */

  if (fd == -1) {  /* open failed: print error message and exit */
    perror("Error in 'open'");
    exit(1);
  }

  printf("Type in some text, and press Enter (or press Ctrl-D)\n");

  n_read = read(0,buf,sizeof(buf));   // read from standard input 0 

  if (n_read == -1) {
    perror("Error in 'read'\n");
    exit(1);
  }
  if (n_read == 0) 
    printf("End of file (EOF)\n");
  
  // close(fd);                          // close file descriptor

  m_written = write(fd,buf,n_read);   // write to the file

  if (m_written == -1) {
    perror("Error in 'write'\n");
    exit(1);
  }

  close(fd);                          // close file descriptor

  printf("Read: %d bytes, written: %d bytes, tekst: %s\n",n_read,m_written,buf);
  printf("See now the file foo!\n");

  exit(0);
}
