Monday, May 15, 2017
Display All The Text Files From A Directory Using C
Display All The Text Files From A Directory Using C
DESCRIPTION:
- This program get the directory path from the user and display all the text files available in the directory.
- We should add dirent.h header file to accomplish this program.
PROGRAM:
#include <string.h>
#include <dirent.h>
#include <string.h>
const char *only_txt (const char *);
int main (int argc, char *argv[])
{
DIR *directory;
struct dirent *file;
directory = opendir (argv[1]);
int directory_length = strlen(argv[1]);
if (directory != NULL){
while (file = readdir (directory)){
if( !strcmp((only_txt (file->d_name)), ".txt") )
puts (file->d_name);
}
(void) closedir (directory);
}
else
perror ("Not able to open the directory ");
return 0;
}
/**load only .txt file**/
#include <dirent.h>
#include <string.h>
const char *only_txt (const char *);
int main (int argc, char *argv[])
{
DIR *directory;
struct dirent *file;
directory = opendir (argv[1]);
int directory_length = strlen(argv[1]);
if (directory != NULL){
while (file = readdir (directory)){
if( !strcmp((only_txt (file->d_name)), ".txt") )
puts (file->d_name);
}
(void) closedir (directory);
}
else
perror ("Not able to open the directory ");
return 0;
}
/**load only .txt file**/
const char *only_txt (const char *filespec)
{
char *file = strrchr (filespec, .);
if (file == NULL)
file = "";
return file;
}
COMPILE:
gcc -o out scan.c
RUN:
- Pass the directory name with the path as argument to the program
./out /home/sujin/directory
test.txt
README.txt
file.txt
CONCLUSION:
Changing ".txt" to any type file extension, you can customize this program for file type you like.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.