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

/* resources not allocated yet */
char *buffer = NULL;
int fd_in = -1,fd_out = -1;

void myexit(int ret);

int main(int argc,char *argv[])
{
	char string[256];
	int nn,ww;
	size_t bufsize = 0;

	if (argc != 4) {
		printf("Uso: %s <dimensione del buffer> <file da copiare> <file da produrre>\n",argv[0]);
		myexit(5);
	}
										/* cast to int because of the sign */
	if (sscanf(argv[1],"%d",&bufsize) != 1 || (int)bufsize <= 0) {
		printf("%s non va bene come <dimensione del buffer>\n",argv[1]);
		myexit(5);
	}
	if ( (buffer = malloc(bufsize)) == NULL ) {
		sprintf(string,"Errore allocando %d bytes",bufsize);
		perror(string); myexit(5);
	}
	if ( (fd_in = open(argv[2], O_RDONLY)) < 0 ) {
		sprintf(string,"Apertura di %1.200s fallita",argv[2]);
		perror(string); myexit(5);
	}										/* try also adding O_SYNC */
	if ( (fd_out = open(argv[3], O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, 00644)) < 0 ) {
		sprintf(string,"Apertura di %1.200s fallita",argv[3]);
		perror(string); myexit(5);
	}
	while( (nn = read(fd_in,buffer,bufsize)) ) {
		if (nn < 0 && errno != EAGAIN && errno != EINTR) {
			sprintf(string,"Errore durante la lettura di %1.200s",argv[2]);
			perror(string); myexit(5);
		}
		ww = write(fd_out,buffer,nn);
		if (ww < 0 || ww != nn) {
			sprintf(string,"Errore durante la scrittura di %1.200s",argv[3]);
			ww < 0 ? perror(string) : printf(string);
			myexit(5);
		}
	}
	myexit(0);
}

void myexit(int ret)
{
/* free the (eventually) allocated resources */
	if (fd_in  >= 0) close(fd_in);
	if (fd_out >= 0) close(fd_out);
	if (buffer >  0) free(buffer);
	exit(ret);
}
-- AntonioValletta - 14 Nov 2001


This topic: Sistemioperativi1 > CopiaUnix
Topic revision: r1 - 2001-11-14 - AntonioValletta
 
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 2008-2024 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback