FindFirstFile Issues can't get any example to work. - c++

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("...")

Related

Name of a named pipe given handle

I'm trying to find the name of a named pipe given it's handle. I found a solution where the named pipe handle is duplicated using NtDuplicateObject and then the name is extracted using NtQueryObject but it's unstable so that's out of the question.
Currently I'm attempting to do so with GetFinalPathNameByHandle but having no luck. I'm not even sure if it's possible to do this but it was mentioned as a potential solution so I'm going with it. The following is adapted from the example code at:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa364962(v=vs.85).aspx
void __cdecl _tmain(int argc, TCHAR *argv[]){
TCHAR Path[BUFSIZE];
HANDLE pipe;
DWORD dwRet;
printf("\n");
if (argc != 2)
{
printf("ERROR:\tIncorrect number of arguments\n\n");
printf("%s <file_name>\n", argv[0]);
return;
}
pipe = CreateNamedPipe(argv[1], PIPE_ACCESS_INBOUND | PIPE_ACCESS_OUTBOUND, PIPE_WAIT, 1,
1024, 1024, 120 * 1000, NULL);
if (pipe == INVALID_HANDLE_VALUE)
{
printf("Could not open file (error %d\n)", GetLastError());
return;
}
dwRet = GetFinalPathNameByHandle(pipe, Path, BUFSIZE, VOLUME_NAME_NT);
if (dwRet < BUFSIZE)
{
_tprintf(TEXT("\nThe final path is: %s\n"), Path);
}
else printf("\nThe required buffer size is %d.\n", dwRet);
CloseHandle(pipe);}
The command line parameter is "\\\\.\\pipe\\mynamedpipe" or "\\.\pipe\mynamedpipe", I've tried both. The output is garbage but more importantly when debugging with Visual Studio 2013 Express while stepping through the program the path variable is garbage directly after the GetFinalPathNameByHandle call.
By garbage I mean:
Path 0x0036fab4 L"쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌... wchar_t[100]
Console output is:
The final path is: ?????????????????????????????????????????????????????????????????????????????????????????????????????????6?╫☻
So I'm officially stuck. Alternatively and possibly a much better solution would be comparing two named pipe handles to each other to determine if they point to the same named pipe. If there is a way to do that it would solve my problem as well.
To answer my own question here. GetFileInformationByHandleEx does exactly this using FileNameInfo for the FileInformationClass parameter and a handle generated by CreateNamedPipe.

Function to remove directory removes it only after debug finishes c++

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 );

Select the last modified file from a directory

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.

Problems with Visual C++: Reading all files in a directory

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.

How to remove a non-empty directory in C++?

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.