All pastes #964809 Raw Edit

Stuff

public text v1 · immutable
#964809 ·published 2008-03-31 15:53 UTC
rendered paste body
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <time.h>
#include <stdlib.h>

typedef enum{false=0,true=1} bool;

void showDir(char *dirname, bool show);
void showFile(const struct dirent *ent, const struct stat *statbuf);
int humanReadableSize(int size);
char *datify(const time_t *date);

int main(int argc, char *argv[])
{
	int i=0;
	char *actual = ".";
	bool show=false;
	
	if(argc == 1)
	{
		showDir(actual, false);
	} else if(argc > 1) {
		show = (argc == 2) ? false : true;
		for(i=1; i<argc; i++) {
			showDir(argv[i], show);
		}
	}
}

void showDir(char *dirname, bool show)
{
	struct dirent *ent;
	struct stat statbuf;
	char directorio[PATH_MAX];
	char fichero[PATH_MAX];
	DIR *d;
	
	getcwd(directorio, PATH_MAX);
	strcat(directorio, "/");
	d = opendir(directorio);
	
	if(show == true) {
		printf("%s/:\n", dirname);
	}
	
	if(d == NULL) {
		printf("no se pudo abrir el directorio %s\n", dirname);
		return;
	}
	while((ent = readdir(d)) != NULL) {
		strcat(directorio, ent->d_name);
		stat(fichero, &statbuf);
		printf("%s\n", fichero);
		if(ent->d_name[0] != '.')
		{
			showFile(ent, &statbuf);
		}
	}
	closedir(d);
	return;
}

void showFile(const struct dirent *ent, const struct stat *statbuf)
{
	int perms[9] = {S_IRUSR, S_IWUSR, S_IXUSR, S_IRGRP, S_IWGRP, S_IXGRP, S_IROTH, S_IWOTH, S_IXOTH};
	unsigned short int i = 0;
	
	printf( (statbuf->st_mode & S_IFDIR) ? "d" : "-" );
	
	// Show the permissions
	for(i = 0; i < 9; i++) {
		if(statbuf->st_mode & perms[i]) {
			switch(i % 3) {
				case 0:
					printf("r");
					break;
				case 1:
					printf("w");
					break;
				case 2:
					printf("x");
					break;
			}
		} else {
			printf("-");
		}
	}
	printf("  %d\t%d\t%d\t%d\t%s\t", statbuf->st_nlink, statbuf->st_uid, statbuf->st_gid,
		humanReadableSize(statbuf->st_size), datify(&statbuf->st_mtime));
	
	if(statbuf->st_mode & S_IFDIR) {
			printf("\033[34m%s/\033[0m\n", ent->d_name);
	} else if(statbuf->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
		printf("\033[32m%s\033[0m\n", ent->d_name);
	} else {
		printf("%s\n", ent->d_name);
	}
}

int humanReadableSize(int size)
{
	int ret=size;
	
	return ret;
}

char *datify(const time_t *date)
{
	char *ret=ctime(date);
	ret [ strlen(ret)-1 ]='\0';
	
	return ret;
}