#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#define BUFSIZE 512

int main(int argc, char * argv[]) {
    char buffer[BUFSIZE];
    int src, dest, errno;
    int nread, nwritten, n;
    int totalr=0, totalw=0;
    if (argc!=3) {
        printf ("Usage: flength source destination\n");
        return (-1); }
    src = open(argv[1], O_RDONLY);
    if (src < 0) {
        perror("Source file could not be opened!");
        return (-1); } 
    dest = open(argv[2], O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR);
    if (dest < 0) {
        perror("Target file could not be opened!");
        return (-2); } 
    while ((nread = read(src, buffer, BUFSIZE))>0) {
  	    nwritten=0;
            do {
                n = write (dest, &buffer[nwritten], nread-nwritten);
                nwritten += n;
               } while (nwritten<nread); }
    close (src);
    close (dest);
    return (0); }
