EvilZone
Programming and Scripting => C - C++ => : m0l0ko July 04, 2012, 04:20:32 AM
-
In PHP, the following code:
scandir("/path/to/directory");
will get a list of all the files in a directory and store it in an array. With that array I can make a loop to read or edit all the files in the directory. How can I do this in C++?
-
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
int main()
{
DIR *dir = opendir (".");
struct dirent *file;
if (dir) {
while ((file = readdir (dir)) != NULL) {
printf ("%s\n", file->d_name);
}
closedir (dir);
}
else printf ("Cannot open dir\n");
return 0;
}
-
Thanks. I'm new to C/C++, does this code load the contents of the directory into an array?
-
Thanks. I'm new to C/C++, does this code load the contents of the directory into an array?
As far as I know, it doesn't. With opendir() you get a folder "descriptor". Then, with readdir() you get info of the files in that folder, one file for each call to readdir().
$ man opendir
$ man readdir
-
#include <windows.h>
#include <string>
#include <iostream>
#include <list>
using namespace std;
void GetFileListing(list<string>& listing, string directory, string fileFilter, bool recursively=true)
{
if (recursively)
GetFileListing(listing, directory, fileFilter, false);
directory += "\\";
WIN32_FIND_DATA FindFileData;
HANDLE hFind = INVALID_HANDLE_VALUE;
string filter = directory + (recursively ? "*" : fileFilter);
hFind = FindFirstFile(filter.c_str(), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
DWORD dwError = GetLastError();
if (dwError!=ERROR_FILE_NOT_FOUND)
{
cout << "Invalid file handle for filter "<<filter<<". Error is " << GetLastError() << endl;
}
}
else
{
if (!recursively)
{
listing.push_back(directory + string(FindFileData.cFileName));
}
while (FindNextFile(hFind, &FindFileData) != 0)
{
if (!recursively)
{
listing.push_back(directory + string(FindFileData.cFileName));
}
else
{
if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)>0 && FindFileData.cFileName[0]!='.')
{
GetFileListing(listing, directory + string(FindFileData.cFileName), fileFilter);
}
}
}
DWORD dwError = GetLastError();
FindClose(hFind);
if (dwError != ERROR_NO_MORE_FILES)
{
cout << "FindNextFile error. Error is "<< dwError << endl;
}
}
}
int main(int argc, char* argv[])
{
list<string> listing;
GetFileListing(listing, "G:", "*.*");
for(list<string>::iterator it = listing.begin(); it!=listing.end();++it)
{
cout << *it << endl;
}
getchar();
return 0;
}
Enjoy