Question

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.

Was it helpful?

Solution

To list files on Windows you can use FindFirstFile() and FindNextFile(). For an example see Listing the Files in a Directory.

OTHER TIPS

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 \\?\.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top