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\n");
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\n");
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.
Some errors:
ReplyDelete- only_txt returns a variable allocated on the stack! it will SIGSEGV soon.
- directory_length unused variable.
- "while (file = readdir (directory)){" warning suggested parenteses.
- puts and perror are defined on
if (directory ..
while (file ...
if( !strcmp((only_txt ...
if( and if ( aand func((. U must choose a standard.
Thanks for your feedback..
ReplyDelete