#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;
FILE *file_in = NULL , *file_out = NULL;

void myexit(int ret);

int main(int argc,char *argv[])
{
	char string[256];
	size_t 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 ( (file_in = fopen(argv[2], "r")) == NULL ) {
		sprintf(string,"Apertura di %1.200s fallita",argv[2]);
		perror(string); myexit(5);
	}
	if ( (file_out = fopen(argv[3], "w")) == NULL ) {
		sprintf(string,"Apertura di %1.200s fallita",argv[3]);
		perror(string); myexit(5);
	}
/* The following line disable the std. library buffering mechanism */
/*	setvbuf(file_out, NULL , _IONBF , 0);*/
	while( (nn = fread(buffer,1,bufsize,file_in)) ) {
		ww = fwrite(buffer,1,nn,file_out);
/* The following force std. library to write the buffer */
/*		if ( fflush(file_out) ) {
			sprintf(string,"Errore durante la scrittura di %1.200s",argv[3]);
			perror(string);
			myexit(5);
		}
*/
		if (ww == 0 || ww != nn) {
			sprintf(string,"Errore durante la scrittura di %1.200s",argv[3]);
			ferror(file_out) < 0 ? perror(string) : printf(string);
			myexit(5);
		}
	}
	if (!feof(file_in)) {
		sprintf(string,"Errore durante la lettura di %1.200s",argv[2]);
		perror(string); myexit(5);
	}
	myexit(0);
}



void myexit(int ret)
{
/* free the (eventually) allocated resources */
	if (file_in  > 0) fclose(file_in);
	if (file_out > 0) fclose(file_out);
	if (buffer	> 0) free(buffer);
	exit(ret);
}	
-- AntonioValletta - 14 Nov 2001
Topic revision: r1 - 2001-11-14 - AntonioValletta






 
Questo sito usa cookies, usandolo ne accettate la presenza. (CookiePolicy)
Torna al Dipartimento di Informatica
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