Reputation: 36237
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.
Upvotes: 2
Views: 172
Reputation: 23560
MinGW (link) has dirent.h
. I have found no documentation about its specific implementation of dirent on the net, but i assume it is similar enough to unix-derivatives version. You can look at the header-file and then decide whether to use it.
Notes about the other answers: I dont know about the version from softagalleria.net, so i cannot talk about it, but about the FindFirstFile/FindNextFile
-API: If you decide to use it make sure to use the "Unicode"-Versions (actually UCS-2) because the Ascii-Versions only allow very limited path-lengths. To use the Unicode-Version define the macro and make sure you prepend all paths with \\?\
.
Upvotes: 0
Reputation: 122001
To list files on Windows you can use FindFirstFile()
and FindNextFile()
. For an example see Listing the Files in a Directory.
Upvotes: 1