Listar arquivos e diretórios com suas propriedades
Publicado por Raphael Silva do Nascimento (última atualização em 08/12/2010)
[ Hits: 12.106 ]
Criei um programa em C que recebe como parâmetro o nome de um ou mais diretórios e lista todos os arquivos, incluindo todas as propriedades de cada arquivo, como se fosse o comando ls -la.
Foi utilizada a sycall stat sys/stat.h.
/*
Name: Status.c
Author: Raphael Silva do Nascimento
Date: 29/11/10
Description: script que recebe como parametro o nome de um ou mais diretórios e lista todos os arquivos incluindo todas as propriedades de cada arquivo, como se fosse o comando ls -la.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <locale.h>
#include <langinfo.h>
#include <stdio.h>
#include <stdint.h>
#include <errno.h>
#include <fcntl.h>
int informacaoArquivo(char* );
int main(int argc, char * argv[]){
int i;
if(argc >= 2){
for(i=1; i<argc; i++){
printf("\n---------------------------%s--------------------------\n\n",argv[i]);
informacaoArquivo(argv[i]);
}
}else{
printf("\n");
informacaoArquivo(".");
}
printf("\n\n");
return;
}
int informacaoArquivo(char *url)
{
struct dirent *dp;
struct stat statbuf;
struct passwd *pwd;
struct group *grp;
struct tm *tm;
char datestring[256];
DIR *dir;
char * accesses[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
ushort mode;
int i=0;
dir = opendir(url);
if (dir==NULL){
perror("Erro ao abrir diretorio");
return;
}
/* Loop atraves da entrada do diretorio */
while (dp = readdir(dir)) {
/* Obter informaçoes de entrada */
stat(dp->d_name, &statbuf);
/* Print o tipo de arquivo */
if(S_ISREG(statbuf.st_mode)) { printf("-"); } //Arquivo regular
if(S_ISDIR(statbuf.st_mode)) { printf("d"); } //Diretorio
if(S_ISCHR(statbuf.st_mode)) { printf("c"); } //Dispositivo de caracter
if(S_ISLNK(statbuf.st_mode)) { printf("l"); } //Link
if(S_ISSOCK(statbuf.st_mode)) { printf("s"); }//Arquivo Socket
/* Print a permissão.*/
for(i = 6; i >= 0; i -=3)
printf("%s", accesses[(statbuf.st_mode >> i) & 7]);
/* Print o numero de link */
mode = statbuf.st_nlink;
printf(" %d", mode);
/* Print o nome do criador se for achado usando getpwuid().*/
if ((pwd = getpwuid(statbuf.st_uid)) != NULL)
printf(" %-8.8s", pwd->pw_name);
else
printf(" %-8d", statbuf.st_uid);
/* Print nome do grupo se for achado usando getgrgid().*/
if ((grp = getgrgid(statbuf.st_gid)) != NULL)
printf(" %-8.8s", grp->gr_name);
else
printf(" %-8d", statbuf.st_gid);
/* Print tamanho do arquivo.*/
printf(" %jd", (intmax_t)statbuf.st_size);
tm = localtime(&statbuf.st_mtime);
/* Obter data em estring. */
strftime(datestring, sizeof(datestring), nl_langinfo(D_T_FMT), tm);
printf(" %s %s\n", datestring, dp->d_name);
}
close(dir);
}
Manipulação de registros em arquivos utilizando índices
Manipulação de arquivos CSV - Estruturado
Cirurgia para acelerar o openSUSE em HD externo via USB
Void Server como Domain Control
Modo Simples de Baixar e Usar o bash-completion
Monitorando o Preço do Bitcoin ou sua Cripto Favorita em Tempo Real com um Widget Flutuante
[Resolvido] VirtualBox can't enable the AMD-V extension
Como verificar a saúde dos discos no Linux
Como instalar , particionar, formatar e montar um HD adicional no Linux?
Como automatizar sua instalação do Ubuntu para desenvolvimento de software.
Não consigo instalar distro antiga no virtualbox nem direto no hd (14)
Quais os códigos mais dificeis que vcs sabem fazer? (12)
systemd-resol... precisa ser reiniciado periodicamente [RESOLVIDO] (7)









