2

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.

Keith Miller
  • 1,337
  • 1
  • 16
  • 32
Boardy
  • 35,417
  • 104
  • 256
  • 447

3 Answers3

1

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

hmjd
  • 120,187
  • 20
  • 207
  • 252
  • I think OP wanted something generic to run on both: `The code needs to run on both Windows and Linux` – Mike Oct 16 '12 at 11:39
  • @mike, I don't think so, given the title of the question and nothing in the question suggests conditional preprocessor code inclusion is not acceptable. – hmjd Oct 16 '12 at 11:41
1

There is a free windows implementation of dirent.h (clicky)

tozka
  • 3,211
  • 19
  • 23
0

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

Bernd Elkemann
  • 23,242
  • 4
  • 37
  • 66