Holas,
vamos a ver los archivos de los directorios en Linux, no es muy dificil.
primero que todo necesitamos esto:
#include sys/types.h
#include dirent.h
las carpetas se abren como si fuesen archivos, osea, se abre la carpteas (opendir()) se obtiene en este caso una estructira DIR, dsp se va leyendo cada uno de los archivos (o carpetas) que contiene la carpeta abierta (readdir()) y cuand terminamos lo cerramos (closedir())
enpezamos con opendir:
DIR *opendir(const char *name);
en "name" ponemos la ruta de la carpeta
solamente tenemos que hacer
#include sys/types.h
#include dirent.h
DIR *d;
d = opendir("/usr/bin");
si opendir retorna 0, hubo error, y podemos visitar errno para averiguar que error es.
ya tenemos abierto el directorio, ahora con readdir:
struct dirent *readdir(DIR *dir);
*dir es lo que nos retorno opendir, y readdir nos da una estructura dirent con informacion de lo que hay en la carpeta. readdir va retornando de a uno, osea, la primera vez que se llama a readdir nos da la primera carpeta (".") la proxima vez que lo llamemos nos da la segunda carpeta ("..") y la tercera vez nos da la tercersera, y asi sucesivamente, cuando no haya mas archivos en el directorio, readdir retorna 0.
dirent esta definida asi:
struct dirent {en d_name tenemo el nombre del archivo, y en d_type el tipo de archivo (comun, directorio, pila, socket, etc.), pero "man" nos dice esto:
ino_t d_ino; /* inode number */
off_t d_off; /* offset to the next dirent */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file */
char d_name[256]; /* filename */
};
tems. This field makes it possible to avoid the expense of calling
stat(2) if further actions depend on the type of the file. If the
_BSD_SOURCE feature test macro is defined, then glibc defines the fol-
lowing macro constants for the value returned in d_type:
DT_UNKNOWN The file type is unknown.
DT_REG This is a regular file.
DT_DIR This is a directory.
DT_FIFO This is a named pipe, or FIFO.
DT_SOCK This is a Unix domain socket.
DT_CHR This is a character device.
DT_BLK This is a block device.
If the file type could not be determined, the value DT_UNKNOWN is
returned in d_type.
asique nose.. a tener cuidado (al final de este post explico stat())
para usar a readdir():
#include sys/types.hnoten que utilizo dire->d_name porque dire es un puntero a una estructura..
#include dirent.h
DIR *d;
struct dirent *dire;
d = opendir("/usr/bin");
if(!d)
return 1; /*error, upsss*/
while((dire = readir(d)) != 0)
printf("/usr/bin/%s", dire->d_name);
muy bien, ahora para cerrar el directorio
int closedir(DIR *dir);
no hay mucho que decir..., solo que en caso de error retorna -1
#include sys/types.h
#include dirent.h
DIR *d;
struct dirent *dire;
d = opendir("/usr/bin");
if(!d)
return 1; /*error, upsss*/
while((dire = readir(d)) != 0)
printf("/usr/bin/%s", dire->d_name);
closedir(d);
que facil no?
bueno, hay mas funciones, solo voy a explicar rewinddir, no creo que las otras sean necesarias, cualquier cosa pueden recurir a "man"
void rewinddir(DIR *dir);
rewinddir() (como el nombre lo dice) se coloca al principio del directorio, asi la proxima llamada a readdir va a dar como resultado el primer archivo.
ahora a explicar stat()
#include sys/types.h
#include sys/stat.h
#include unistd.h
int stat(const char *path, struct stat *buf);
int fstat(int fd, struct stat *buf);
stat y fstat son lo mismo, la diferencia es que a stat() le indicas el nombre del archivo/carpeta y en fstat le indicas un descriptor de archivo/carpeta (la funcion open() tambien abre carpetas...)
lo que hace stat es colocar en "buf" informacion sobre el archivo especificado, y la informacion es:
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for filesystem I/O */
blkcnt_t st_blocks; /* number of blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last status change */
};
no hay que aclarar mucho, solo especifico a la variable st_mode:
(estas son bit flags)
S_IFSOCK 0140000 socket
S_IFLNK 0120000 symbolic link
S_IFREG 0100000 regular file
S_IFBLK 0060000 block device
S_IFDIR 0040000 directory
S_IFCHR 0020000 character device
S_IFIFO 0010000 FIFO
S_ISUID 0004000 set UID bit
S_ISGID 0002000 set-group-ID bit (see below)
S_ISVTX 0001000 sticky bit (see below)
S_IRWXU 00700 mask for file owner permissions
S_IRUSR 00400 owner has read permission
S_IWUSR 00200 owner has write permission
S_IXUSR 00100 owner has execute permission
S_IRWXG 00070 mask for group permissions
S_IRGRP 00040 group has read permission
S_IWGRP 00020 group has write permission
S_IXGRP 00010 group has execute permission
S_IRWXO 00007 mask for permissions for others (not in group)
S_IROTH 00004 others have read permission
S_IWOTH 00002 others have write permission
S_IXOTH 00001 others have execute permission
osea, por ejemplo para saber si es un directorio hay que hacer
if(st_mode & S_IFDIR)
/*es directorio!*/
else
/*no lo es :(*/
(lo mismo para saber quieens tienen permisos de hacer que con el archivo, solo hay que usar el AND)
o bien, utilizar unas macros que nos brinda
S_ISDIR(m) directory?
S_ISCHR(m) character device?
S_ISBLK(m) block device?
S_ISFIFO(m) FIFO (named pipe)?
S_ISLNK(m) symbolic link? (Not in POSIX.1-1996.)
S_ISSOCK(m) socket? (Not in POSIX.1-1996.)
bueno, creo que eso es todo...
salu2!

:





