I am currently working on a C project where I need to scan a directory and get the file name for each file within that directory. The code needs to run on both Windows and Linux. I have the linux version using the following code.
DIR *dp;
int i = 0;
struct dirent *ep;
char logPath[FILE_PATH_BUF_LEN];
sprintf(logPath, "%s/logs/", logRotateConfiguration->logFileDir);
printf("Checking pre existing log count in: %s\n", logPath);
dp = opendir(logPath);
if (dp != NULL)
{
while ((ep = readdir(dp)) != NULL)
{
if (strcmp(ep->d_name, ".") != 0 && strcmp(ep->d_name, "..") != 0)
{
i = i + 1;
}
}
closedir(dp);
}
else
{
perror("Couldn't open directory");
}
logRotateConfiguration->logCount = i;
For this code to work I am using the #include <dirent.h> but have found this to not be compatible for Windows. Therefore in my header file I have used an ifdef to include dirent.h if on Linux but not sure what I can use for it being on Windows.
Thanks for any help you can provide.
To list files on Windows you can use
FindFirstFile()andFindNextFile(). For an example see Listing the Files in a Directory.