List segments

From Sistemi Operativi
Revision as of 16:52, 9 December 2014 by Maldus (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Il seguente programma svolge la funzione del comando ls, cioè elenca il contenuto della directory passata come argomento, specificando se è un file o una directory a sua volta.

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

#define SIZE 100 

int main(int argc, char *argv[]){
	int f = open( argv[1] , O_RDONLY ) ;
	struct stat buf;	/*struttura di informazioni su un file*/
	DIR* dir ;
	struct dirent *I ;	/*struttura di informazioni sulle entry di una directory*/
	char *type ;
	char path[SIZE] ;
	if (fstat(f , &buf) != 0) perror("lstat error");	/*fstat reimpie buf con le dovute informazioni sul file di cui f è il descrittore*/
	if( !(S_ISDIR(buf.st_mode)) ){
		printf( "argument is not a valid directory\n" ) ;
		return 0 ;
	}
	dir = fdopendir( f ) ;
	I = readdir( dir ) ;
	while(I){
		strcpy(path , argv[1] ) ;	/*nella stringa path costruisco il percorso per la entry che sto considerando, in modo da poterne visualizzare 
le informazioni e saper dire se è un file o una directory*/
		strcat( path , "/" ) ;
		strcat( path , I->d_name ) ;
		if( lstat( path , &buf) < 0 ) perror("lstat error");
		if(S_ISREG(buf.st_mode))  type = "regular file";
    		else if (S_ISDIR(buf.st_mode))  type = "directory";
		else type = "what?" ;
		printf("%s: %s\n" , type ,  I->d_name ) ;
		I = readdir( dir ) ;
	}
	return 0 ;
}

Dalle prove che ho fatto sembra funzionare, salvo per un dettaglio che non riesco a spiegarmi: in ogni directory elenca, oltre agli elementi presenti, due directory extra, "." e "..".

Maldus (talk) 18:32 Sunday, 7 December 2014 (CET)