I need to know, how I can select the Last modified/created file in a given directory.
I currently have a directory named XML, and inside that there are many XML files. But I would like to select only the last modified file.
I use the following function to list all the items inside a folder. It writes all the files in a string vector, but you can change that.
bool ListContents (vector<string>& dest, string dir, string filter, bool recursively)
{
WIN32_FIND_DATAA ffd;
HANDLE hFind = INVALID_HANDLE_VALUE;
DWORD dwError = 0;
// Prepare string
if (dir.back() != '\\') dir += "\\";
// Safety check
if (dir.length() >= MAX_PATH) {
Error("Cannot open folder %s: path too long", dir.c_str());
return false;
}
// First entry in directory
hFind = FindFirstFileA((dir + filter).c_str(), &ffd);
if (hFind == INVALID_HANDLE_VALUE) {
Error("Cannot open folder in folder %s: error accessing first entry.", dir.c_str());
return false;
}
// List files in directory
do {
// Ignore . and .. folders, they cause stack overflow
if (strcmp(ffd.cFileName, ".") == 0) continue;
if (strcmp(ffd.cFileName, "..") == 0) continue;
// Is directory?
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
// Go inside recursively
if (recursively)
ListContents(dest, dir + ffd.cFileName, filter, recursively, content_type);
}
// Add file to our list
else dest.push_back(dir + ffd.cFileName);
} while (FindNextFileA(hFind, &ffd));
// Get last error
dwError = GetLastError();
if (dwError != ERROR_NO_MORE_FILES) {
Error("Error reading file list in folder %s.", dir.c_str());
return false;
}
return true;
}
(don't forget to include windows.h)
What you have to do is adapt it to find the newest file.
The ffd structure (WIN32_FIND_DATAA data type) contains ftCreationTime, ftLastAccessTime and ftLastWriteTime, you can use those to find the newest file.
These members are FILETIME structures, you can find the documentation here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms724284%28v=vs.85%29.aspx
You can use FindFirstFile and FindNextFile, they deliver a struct describing the file like size as well as modified time.
Boost.Filesystem offers last_write_time. You can use this to sort the files in a directory. Boost.Filesystem and (Boost) in general can be a little bit intimidating for a C++ new-comer so you might want to check a solution for your OS first.
Related
I wrote a simple code to do some operation on every file in every folder (subfolders).
It's perfectly works until the path comes with 'SPACE
' character program crashs and INVALID_HANDLE_VALUE has been called. This is function:
int dirListFiles(char* startDir)
{
HANDLE hFind;
WIN32_FIND_DATAA wfd;
char path[MAX_PATH];
sprintf(path, "%s\\*", startDir);
std::string fileName;
std::string s_path = startDir;
std::string fullPath;
fprintf(stdout, "In Directory \"%s\"\n\n", startDir);
if ((hFind = FindFirstFileA(path, &wfd)) == INVALID_HANDLE_VALUE)
{
printf("FindFirstFIle failed on path = \"%s\"\n", path);
abort();
}
BOOL cont = TRUE;
while (cont == TRUE)
{
if ((strncmp(".", wfd.cFileName, 1) != 0) && (strncmp("..", wfd.cFileName, 2) != 0))
{
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
sprintf(path, "%s\\%s", startDir, wfd.cFileName);
dirListFiles(path);
}
else
{
fileName = wfd.cFileName;
fullPath = s_path + "\\" + fileName;
std::string fileExt = PathFindExtension(fullPath.c_str());
if (fileExt == ".cpp")
{
... Some operation on file
}
}
}
cont = FindNextFile(hFind, &wfd);
}
FindClose(hFind);
For example, If FindNextFile wants to Open Program Files (x86) which has space between file name cause error and program exit. What Can I do for supporting spaces? What Is Problem?
Space is legal character in directory and file names.
First I propose to modify slightly your code:
if ((hFind = FindFirstFileA(path, &wfd)) == INVALID_HANDLE_VALUE)
{
printf("FindFirstFIle failed on path = \"%s\". Error %d\n", path, GetLastError());
return 0; // I think you shouldn't abort on error, just skip this dir.
}
Now check error codes reported by your program.
For some paths I have got error #5 (access denied). Examples:
c:\Program Files (x86)\Google\CrashReports\*
c:\ProgramData\Microsoft\Windows Defender\Clean Store\*
c:\Windows\System32\config\*
Got two cases with code #123 (Invalid name) for path names unmanageable by FindFirstFileA. To correct this behavior it would be better to use wide version of function FindFirstFileW. See both answers for c++ folder only search. For new Windows applications you should use wide version of API, converting with MultiByteToWideChar and WideCharToMultiByte if needed.
You have also logic error. Code skips all directories and files starting with dot.
I keep having issues with the FindFirstFile and FindNextFile I need to get them to list all dlls into an array but I cant get it to list any files. I have tried using and editing the example code from MSDN but that doesn't work either they pass the wrong type of variable to a function. The code I have now is below sorry if it's a mess but I am trying everything to get it to work. I was also using argv[1] because I believe that gives the directory of the .exe which is what I need because that were the dlls will be stored. I am completely confused by why all the examples I try don't work and why I can't amend them to work.
WIN32_FIND_DATA FindFileData;
HANDLE hFind = INVALID_HANDLE_VALUE;
string directorySearch = "E:\\My Documents\\Visual Studio 2010\\Projects\\SEP-Asignment-One\\Debug\\*";
// Find the first file in the directory.
hFind = FindFirstFile(LPCWSTR("E:\\My Documents\\Visual Studio 2010\\Projects\\SEP-Asignment-One\\Debug\\*"), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
printf ("Invalid file handle. Error is %u.\n", GetLastError());
}
else
{
printf ("First file name is %s.\n", FindFileData.cFileName);
// List all the other files in the directory.
while (FindNextFile(hFind, &FindFileData) != 0)
{
printf ("Next file name is %s.\n", FindFileData.cFileName);
}
FindClose(hFind);
Any Help would be apreceated.
Use std::wstring, wide string literals like L"Hello", and remember to defined UNICODE before including <windows.h> (but that's done by default in a Visual Studio project).
Instead of
hFind = FindFirstFile(LPCWSTR("...")...,
try
hFind = FindFirstFile(_T("...")
I have this code in c++ to remove directory that includes files in it:
void* hFind = INVALID_HANDLE_VALUE;
WIN32_FIND_DATA ffd;
hFind = FindFirstFile((fullpath+"\\" + _docname + "\\"+"*").c_str(), &ffd);
do //delete all the files in the directory
{
// check if it is a file
if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
string s = (fullpath+_docname+"\\").append(ffd.cFileName);
remove(s.c_str());
}
}
while (FindNextFile(hFind, &ffd) != 0);
removeDirectory(fullpath+"\\" + _docname);
FindClose(hFind);
The problem is - the directory is actually removed only after I close the dubugger.
While debugging, the directory is inaccessible, but still exists, and it make me troubles.
Do you know how can I fix it to tottaly remove the folder?
swapping the last two lines might fix this: close the handle before removing the directory
FindClose( hFind );
removeDirectory( fullpath + "\\" + _docname );
I'm trying to read all files in a directory. I have the following code:
void scanDirectory(char* dir)
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind = INVALID_HANDLE_VALUE;
char DirSpec[MAX_PATH]; // directory specification
strcpy(DirSpec, dir);
strcat(DirSpec, "\\*");
hFind = FindFirstFile(DirSpec, &FindFileData);
int i = 0;
do {
i++;
printf("%d \n", i);
if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
printf(" %s <DIR>\n", FindFileData.cFileName);
}
else
{
printf("File %s\n", FindFileData.cFileName);
}
} while(!FindNextFile(hFind, &FindFileData));
FindClose(hFind);
}
The problem is that when I execute the code it results in an infinite loop. Also the output characters are strange, like "File ".
I think you are not using chars and wide chars in a consequent way. You should either use functions with wide char and wchar_t type or vice versa. (But it was a compile error for me so it may depend on some kind of project settings as well.)
And your exit condition in the while loop is also wrong it should test for FindNextFile and not !FindNextFile. The infinite loop may be because of this condition as if it doesn't find any files it will run forever.
Also you should test for the return value of FindFirstFile and not go into the loop if it doesn't find any files.
You are calling !FindNextFile instead of FindNextFile, also you are not checking why
the FindNextFile fails, so you can't be sure if all the files were processed.
Use something like this.
WIN32_FIND_DATA stFindData;
HANDLE hFind = FindFirstFile(cSearchPattern, &stFindData);
if(hFind != INVALID_HANDLE_VALUE)
{
do
{
// Process File
}
while (FindNextFile(hFind, &stFindData) != 0);
DWORD dwError = GetLastError();
if (dwError != ERROR_NO_MORE_FILES)
{
// Not All Files processed, deal with Error
}
FindClose(hFind);
}
Can't you just use .Net like below:
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(Path);
System.IO.FileInfo[] files = dir.GetFiles();
foreach (System.IO.FileInfo file in files)
{
// Do whatever you need with the file info...
string filename = file.Name;
string fullFilename = file.FullName;
}
This is a c# example but you can use for each in C++ the same. Hope this helps.
In C++, how can I remove a directory with all its contained files? I know there is rmdir, but it will only remove non-empty directories, so how do I list and remove all contained files first?
I know it shouldn't be hard using Boost Filesystem, but I kind of want to avoid building and depending on it just for this one little task ...
Yes, you normally have to remove the contents first. If you don't want to use Boost for this, you're pretty much stuck with writing non-portable code to find all the files (e.g., FindFirstFile, FindNextFile on Windows, opendir, readdir on Unix and similar) recursively, and remove all of them.
On Windows, you can also use ShFileOperation or the IFileOperation interface. These can handle a recursive delete internally, so you just give it the name of the directory you want removed, and it handles the rest.
As with most COM things, the IFileOperation interface seems to be designed specifically to be as clumsy as possible (e.g., IFileOperation::DeleteItem doesn't actually delete anything--it just adds an item to a list of things to be deleted. Then you have to call IFileOperation::PerformOperations to do the actual deletion.
You can use the following code to delete a non-empty directory. This uses Unix-style commands but can be compiled for Windows using Cygwin (if you don't mind depending on the Cygwin DLL).
void delete_folder_tree (const char* directory_name) {
DIR* dp;
struct dirent* ep;
char p_buf[512] = {0};
dp = opendir(directory_name);
while ((ep = readdir(dp)) != NULL) {
sprintf(p_buf, "%s/%s", directory_name, ep->d_name);
if (path_is_directory(p_buf))
delete_folder_tree(p_buf);
else
unlink(p_buf);
}
closedir(dp);
rmdir(directory_name);
}
int path_is_directory (const char* path) {
struct stat s_buf;
if (stat(path, &s_buf))
return 0;
return S_ISDIR(s_buf.st_mode);
}
First of all, any file i/o -- particularly directory changes, is very much OS dependent.
But, for the most part, it's a) deleted the files, then b) remove the directory. (any shortcut to that would definitely be OS dependent, and often OS version depedent)
You'll need to loop over all the files in the directory and delete those first. The code is platform dependent though (as others have mentioned).
For example the code on this MSDN page (from which this is extracted so there will be undefined variables) will work for Windows, but not Unix/Linux:
HANDLE hFind = FindFirstFile(szDir, &ffd);
if (INVALID_HANDLE_VALUE == hFind)
{
DisplayErrorBox(TEXT("FindFirstFile"));
return dwError;
}
// List all the files in the directory with some info about them.
do
{
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
_tprintf(TEXT(" %s <DIR>\n"), ffd.cFileName);
}
else
{
filesize.LowPart = ffd.nFileSizeLow;
filesize.HighPart = ffd.nFileSizeHigh;
_tprintf(TEXT(" %s %ld bytes\n"), ffd.cFileName, filesize.QuadPart);
}
}
while (FindNextFile(hFind, &ffd) != 0);
dwError = GetLastError();
if (dwError != ERROR_NO_MORE_FILES)
{
DisplayErrorBox(TEXT("FindFirstFile"));
}
FindClose(hFind);
prints the file information, but adapting it to delete shouldn't be too hard.
You'll need to call this recursively for all sub directories in the tree.