#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include <unistd.h>

#define BUFLEN 4096

char* filename="myfile.txt"; /* Default filename */

void main( int argc, char* argv[] )
{
  int n;
  int fd_out;
  char buf[BUFLEN];

  if (argc>1) filename = argv[1];

  /* creat a new file */
  if ( (fd_out = creat(filename, 0755)) == -1)
  {
    printf("ERROR 1: can't create file\n");
    return;
  }

  /* Read from stdout, write to file */
  while ( (n=read(0,buf,BUFLEN)) > 0 ) {
    write(fd_out, buf, n); /* Why do we use n and not BUFLEN? */
  }

  close(fd_out);

  return;
}
