1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| #include <limits.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <dirent.h>
int opt_follow_links = 0;
int opt_apparent_size = 0;
int valid_name(const char* name){
return(strcmp(name,".") && strcmp(name,"..")); /*strcmp()renvoie 0 si aucune difference entre les 2 chaines*/
}/*valid_name*/
/*la fonction du_file retourne la taille occupée par le fichier désigné et ses sous rep SANS suivre les liens dc taille liens = taille occupé par le lien et non ce qu'il vise*/
int du_file(const char* pathname){
struct stat st;
int status;
int size;
status = lstat(pathname,&st);
/*cas fichier ou lien*/
if(S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)){
if(opt_apparent_size == 0){
return st.st_size; /* equivaut a "return opt_apparent_size?st.st_size:st.st_blocks" */
}else{
return st.st_blocks;
}
}
/*cas repertoire*/
if(S_ISDIR(st.st_mode)){
DIR* dirp;
struct dirent *dp;
char * entry_path;
entry_path = malloc(PATH_MAX * sizeof(char));
if(opt_apparent_size == 0){
size = st.st_size;
}else{
size = st.st_blocks;
}
dirp = opendir(pathname);
while( (dp=readdir(dirp)) ){
if(valid_name(dp->d_name)){
snprintf(entry_path,PATH_MAX,"%s/%s",pathname,dp->d_name);
size += du_file(entry_path);
printf("%i %s\n",du_file(entry_path),entry_path); /*pr afficher le detail des fichiers/reps de la cible*/
}/*if*/
}/*while*/
return size;
}
/*cas LIEN*/
if((S_ISLNK(st.st_mode)) && (opt_follow_links == 1)){
char linkpath[PATH_MAX];
status = readlink(pathname,linkpath,PATH_MAX);
if (status > 0){
linkpath[status] = '\0';
size += du_file(linkpath);
}
return size;
}
printf("entrée %s ignorée\n",pathname);
return 0;
}/*du_file*/
int main(int argc ,char** argv){
int j = 1;/*car argv[0] est le nom de la commande*/
int i;
/* les otpions sont de la forme "-xyz" avec x,y,z des opts differentes */
if(argv[j][0]=='-'){
j++;/* on incremente pr ke j = 2 pr ke argv[j] soit le pathname pr la suite*/
for (i = 1; i < strlen(argv[1]); i++) {
switch(argv[1][i]) {
case 'b' : {
opt_apparent_size= 1;
break;
}
case 'l' : {
opt_follow_links = 1;
break;
}
}/*switch*/
}
}/*fin options*/
printf("opt1: %i opt2: %i \n",opt_apparent_size,opt_follow_links);
printf("pathname = %s\n",argv[j]);
if(valid_name(argv[j])){
printf("la taille est de : %i \n",du_file(argv[j]));
}else{
printf("erreur\n");
}
return 0;
}/*fin mdu*/ |
Partager