/* C program read all text files from a directory */
Different file system types may
have different directory entries. The dirent structure defines a file system
independent directory entry, which contains information common to directory
entries in different file system types. A set of these structures is returned
by the getdents(2) system call.
The dirent structure is defined as:
#include<sys/dirent.h>
struct dirent
{
long
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*/
};
d_ino ….. inode number of a file
d_offset …..
offset of that directory entry in the actual file system directory
d_name …..
name of the file or directory
d_reclen record length of this entry
d_type …..
type of file( text file, block file, directory etc)
/* Unix program to read all text files from a directory */
/printfile.c*/
#include<stdio.h>
#include<dirent.h>
#include<stdlib.h>
void main()
{
DIR *dirp;
struct dirent *dp;
if((dirp=opendir("/home/kumar"))==NULL) /* trying to open kumar directory*/
{
printf("\n
cannot open");
exit(1);
}
for(dp=readdir(dirp);dp!=NULL;dp=readdir(dirp))
{
if(dp->d_type==DT_REG) /*
printing only if file is a text file */
printf("%s\n",dp->d_name);
}
closedir(dirp);
}
output:
/home/kumar/~$ cc printfile.c
/home/kumar/~$ ./a.out
hello.sh
count.sh
check.sh
semlock.c
pipedemo.c
opendir(), closedir(), readdir() and dirent system call. C program read all text files from a directory. c program to print directory structure. c program to print no of hard links and soft links of a given file
thankyou for helping
ReplyDelete