ProvaPratica 2009.09.23

From Sistemi Operativi
Revision as of 14:59, 30 April 2014 by Mirk M (talk | contribs) (Created page with "<h1>http://www.cs.unibo.it/~renzo/so/pratiche/2009.09.23.pdf</h1> == Esercizio 1 == <syntaxhighlight lang="C"> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #in...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

http://www.cs.unibo.it/~renzo/so/pratiche/2009.09.23.pdf

Esercizio 1

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

#define BUFSIZE 4096

void buf_invert(char *b_input, char *b_output)
{
	int i;

	for(i=0; i<BUFSIZE; i++)
	{
		if(b_input[i] == EOF)
			break;
		b_output[i] = b_input[BUFSIZE-i];
	}
}

off_t file_dim(char *path)
{
	struct stat buf;
	int ris;

	ris = stat (path, &buf);
	if(ris == -1)
	{
		printf("Stat, error %d: %s\n", errno, strerror(errno));
		return -1;
	}

	return buf.st_size;
}

int invert(int input, int output, off_t file_size)
{
	char b_input[BUFSIZE], b_output[BUFSIZE];
	int rris, wris;
	off_t i=0;

	while(i < file_size)
	{
		rris = pread(input, b_input, BUFSIZE, i);
		if(rris == -1)
		{
			printf("Pread error %d: %s\n", errno, strerror(errno));
			return -1;
		}

		i += rris;

		wris = pwrite(output, b_output, BUFSIZE, file_size-i);
		if(wris == -1)
		{
			printf("Pwrite error %d: %s\n", errno, strerror(errno));
			return -1;
		}

		if(rris != wris)
		{
			printf("Invert error\n");
			return -1;
		}
		
	}

	return 0;
}

int main(int argc, char *argv[])
{
	int input, output, ris;
	off_t file_size;

	if(argc > 3)
	{
		printf("Too many arguments\n");
		return -1;
	}

	input = open(argv[1], O_RDONLY);
	if(input == -1)
	{
		printf("Open error %d: %s\n", errno, strerror(errno));
		return -1;
	}

	file_size = file_dim(argv[1]);
	if(file_size == -1)
	{
		printf("File_dim error\n");
		return -1;
	}
	
	printf("File size %d\n", file_size);

	output = open(argv[2], O_CREAT | O_RDWR /*| O_APPEND*/);
	if(output == -1)
	{
		printf("File creation (open) error %d: %s\n", errno, strerror(errno));
		return -1;
	}

	ris = invert(input, output, file_size);
	if(ris == -1)
	{
		printf("Invert error\n");
		return -1;
	}
	
	return 0;
}

Mirko_M