Monday, July 27, 2009

Getting the number of files in a folder/directory using C?

Can anyone show me the code in C that gets the number of files in a folder/directory using "stdio.h".

Getting the number of files in a folder/directory using C?
You can use the dirent.h


This example may help you





#include %26lt;dirent.h%26gt;


#include %26lt;stdio.h%26gt;





int main(){


struct dirent **dent= NULL;


int nE;


int i;


nE = scandir (".", %26amp;dent, NULL, NULL);


for (i=0; i%26lt;nE; i++){


if(dent[i]-%26gt;d_type == DT_DIR)


printf("Directory -%26gt; ");


printf ("%s\n", dent[i]-%26gt;d_name);


free (dent[i]);


dent[i] = NULL;


}





free (dent);


dent = NULL;


}








but if you need to use only the stdio.h, you can use this litle trick





whith popen





NAME


popen, pclose - initiate a pipe to or from a process





SYNOPSIS


#include %26lt;stdio.h%26gt;





FILE *popen(const char *command, const char *mode);





int pclose(FILE *stream);








with this you can call a "ls" command in UNIX systems and you can get what you want


the list of files and dirs





#include %26lt;stdio.h%26gt;





int main(){


FILE *file=NULL;


char var[1024];


fichero = popen ("/bin/ls -l", "r");


if (fichero == NULL){


perror ("Could not open /bin/ls");


exit (-1);


}


fgets (var, 1024, file);


while (!feof (file)){


printf ("%s", var);


fgets (var, 1024, file);


}


pclose (file);


return 0;


}
Reply:I wanted to say that csanon link was most helpful for me. THANK YOU!!! Report It

Reply:Actually, you can’t do this through the stdio functions. While there are functions to open a specific file, getting a list of all files in a specified directory is OS specific.





There’s two ways to deal with this, but I’ll tell you the most logical way. Find out the APIs for your OS. I found one link for Windows API + C++: http://www.codeguru.com/forum/showthread... although the WinAPI itself is accessible through C.





You can Google search on this. Mention your OS in the search query, because it matters.


No comments:

Post a Comment