I am working on a small project in C (Just C not ++ or #) and I was wondering if there was a way that any of you knew of to scan a file/s (Say just its name and or extension)?
Thanks for any help that you can give.
I am working on a small project in C (Just C not ++ or #) and I was wondering if there was a way that any of you knew of to scan a file/s (Say just its name and or extension)?
Thanks for any help that you can give.
You can read the content of a folder (in the following example the current working example) using this code that will print all files (and folder):
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
int main (void) {
DIR *dp;
struct dirent *ep;
dp = opendir("."); // open the current directory
if (dp != NULL) {
while ((ep = readdir(dp)) != NULL) { // read its content one by one
printf("%s\n", ep->d_name);
}
closedir(dp); // close the handle
}
else
perror("Can not access dir");
return 0;
}
You can of course parse the individual file names for their extension in a next step. Note that this example is for Linux.
I asked this question on another forum and got a great answer almost straight away.
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main (void)
{
DIR *dp;
struct dirent *ep;
dp = opendir ("./");
const int MAXFILES = 100;
char list[MAXFILES][256];
int c = 0;
if (dp != NULL)
{
while ((ep = readdir (dp)) && (c < MAXFILES)){
strcpy(list[c],ep->d_name);
++c;
}
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");
return 0;
}