// file_test.c - a tiny demo how to work with files

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

int main(int argc,char *argv[])
{
  char *filename = NULL;
  char *output = "This is written to the file";
  char *out2 = "bla";
  char *buf = NULL;
  int handle = 0;
  int bytes_written = 0;
  int bytes_read = 0;

  if (argc < 2)
  {
    printf("usage: %s <filename>\n",argv[0]);
    return(-1);
  }

  filename = argv[1];
  handle = open(filename,O_CREAT | O_RDWR | O_TRUNC,
                S_IRUSR | S_IWUSR);
  if (handle < 0)
  {
    printf("something went wrong with creation\n");
    return(-1);
  }
  bytes_written = write(handle,output,strlen(output));
  printf("%d bytes were written to %s\n",bytes_written,filename);
  if (close(handle) < 0)
  {
    printf("something went wrong with close\n");
    return(-1);
  }
      // open it again for reading and writing
  handle = open(filename,O_RDWR);
  if (handle < 0)
  {
    printf("something went wrong with re-open\n");
    return(-1);
  }
  buf = malloc(sizeof(char) * 10);
  bytes_read = read(handle,buf,9);
  buf[9] = '\0';
  printf("read from file: %s\n",buf);
  bytes_written = write(handle,out2,strlen(out2));
  printf("%d bytes were written to %s\n",bytes_written,filename);
  if (close(handle) < 0)
  {
    printf("something went wrong with close\n");
    return(-1);
  }  
}
