ProvaPratica 2014.01.23

From Sistemi Operativi
Revision as of 14:50, 23 March 2014 by Pirata (talk | contribs) (Created page with "[C esercizi 1 e 2] <syntaxhighlight lang="C"> /* *Esercizio 1: Linguaggio C (obbligatorio): (20 punti) *Scrivere un programma in C “linean” che prenda come parametro il pa...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

[C esercizi 1 e 2]

/*
*Esercizio 1: Linguaggio C (obbligatorio): (20 punti)
*Scrivere un programma in C “linean” che prenda come parametro il pathname di un file e un numero intero (che chiameremo n). 
*Il programma deve stampare come output il numero di caratteri presenti nella n-ma riga del file se il file e' un file regolare di testo, non deve stampare nulla negli altri casi.
*Un file viene considerato di testo se tutti i suoi byte hanno valori compresi nel range 1-127.
*Per controllare se il file e' “regolare” usare la system call lstat
*/

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



#define BUFFSIZE 200




int istextfile( FILE *fd ){                                   //check if the file is a regular file of text,it means that every byte has a value between 1-127
	int c;
	while ( (c = getc ( fd ) ) != EOF && c <= 127 );
	rewind(fd);                                           //sets the file's cursor at the beginning,otherwise the linean program cannot find the line
	return ( (c == EOF)? 1 : 0 );
}
	 
		
   





void linean( char *path , int line ){
	FILE *fd;
	struct stat buf;
	char bufline[BUFFSIZE];
	char *res;
	int n = line;
	res = NULL;
	lstat( path , &buf );
	if ( S_ISREG( buf.st_mode ) )
	{
		fd = fopen( path , "r" );
		if ( fd == NULL )
		{
			perror( "Error to open the file\n" );
			exit(1);
		}
			if ( istextfile( fd ) )
			{
				while ( ( line > 0 ) )                                        //iterates until at the nline and when is reached then checks if the buffer contains something
				{
					res = fgets(bufline, BUFFSIZE , fd );    //every time the nline is buffered,when exits from the cicle, the buffer contains the nline 
					line--;
				}
				if ( res != NULL )                
				{
					printf( "The file %s in line %d has : %d char\n" , path , n , ( strlen( bufline ) - 1 )  );  //strlen also consider the carriage return
				}
				else
				printf( "Error: isn't possible to find the line\n" );
			}
			else
				printf( "Error is not a regular file of text\n" );
				
		fclose(fd);
				
	}
	else
		printf( "The file %s isn't a regular file\n" , path );
	
	
}

	
	
int main( int argc , char *argv[] ){
	int n = atoi( argv[2] );
	linean( argv[1] , n );
	return(0);
}

Pirata