Prova pratica 2017.01.17

From Sistemi Operativi
Revision as of 14:16, 2 May 2017 by Renzo (talk | contribs) (Created page with "<syntaxhighlight lang=C> #include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> struct fileelem { dev_t ...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

struct fileelem {
	dev_t dev; 
	ino_t ino;
	struct fileelem *next;
};

int addfile(struct fileelem **head, dev_t dev, ino_t ino) {
	if (*head == NULL) {
		*head = malloc(sizeof(struct fileelem));
		(*head)->dev = dev;
		(*head)->ino = ino;
		(*head)->next = NULL;
		return 1;
	} else if ((*head)->dev == dev && (*head)->ino == ino) {
		return 0;
	} else {
		return addfile(&((*head)->next), dev, ino);
	}
}

int filt(const struct dirent *elem) {
	if (strcmp(elem->d_name,".") == 0 ||
			strcmp(elem->d_name,"..") == 0)
		return 0;
	else {
		return 1;
	}
}

int recscan(char *path, struct fileelem **head) {
	struct dirent **list;
	int count = 0;
	int n = scandir(path, &list, filt, alphasort);
	int i;
	for (i = 0; i < n; i++) {
		struct stat buf;
		char *filepath;
		asprintf(&filepath,"%s/%s",path,list[i]->d_name);
		stat(filepath, &buf);
		switch (buf.st_mode & S_IFMT) {
			case S_IFREG:
				count += addfile(head, buf.st_dev, buf.st_ino);
				printf("file %s %ld %ld ... %d\n",filepath,buf.st_dev,buf.st_ino,count);
				break;
			case S_IFDIR:
				count = count + recscan(filepath, head);
				break;
		}
		free(filepath);
		free(list[i]);
	}
	free(list);
	return count;
}

int main(int argc, char *argv[]) {
	struct fileelem *head = NULL;
	int result;
	if (argc > 1)
		chdir(argv[1]);
	result = recscan(".", &head);
	printf("Num of independent files: %d\n", result);
}