Thursday, July 11, 2013

Directory Lister using c language

The command line argument is the folder to be listed. for example if we want ot list hte file names
in the folder images in the c drive we have to specify it as C:\images\.
we need dirent.h file for the code to work. it is open source header file.

#include "stdafx.h"
#include <dirent.h>
#include <conio.h>

int main(int argc,char ** argv)
{
DIR *dp;
struct dirent *ep;
if(argc<2)
{
printf("Insufficinet number of arguments");
return -1;
}
dp = opendir (argv[1]);
while(ep=readdir(dp))
{
puts(ep->d_name);
}
closedir(dp);
puts("Press any key to return");
_getch();
return 0;
}

           The program takes the one argument. that is the folder absolute path to get the file names with the extension. dp is the pointer to the folder or directory to be listed. ep points to the file in the folder. the while loop continuously iterates through the folder or directory. when there is no more files to list then this returns the null then the condition in the while loop becomes void and the loop breaks. ep is the pointer to the currently selected file in the directory. ep->d_name gives the file name currently pointed along with the extension of the file. after completing our task we have to close the directory which is opened in the program.
if we forgot to close then the directory will be closed when we exit the program. based on the need we can modify the code to get the desired files with the specific extension.



No comments:

Post a Comment

DC motor control with Pulse Width Modulation Part 1

DC Motor intro DC motor is a device which converts electrical energy into kinetic energy. It converts the DC power into movement. The typica...