IsProcessRunning function always returns false - c++

IsProcessRunning returns always false, why? notepad is 100% running! I even tried the built version but still not working... It's strange, I can't find a solution via Google :/
#include <iostream>
#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>
using namespace std;
bool IsProcessRunning(const wchar_t *processName)
{
bool exists = false;
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(snapshot, &entry))
while (Process32Next(snapshot, &entry))
if (!wcsicmp(entry.szExeFile, processName))
exists = true;
CloseHandle(snapshot);
return exists;
}
int main()
{
if(IsProcessRunning(L"notepad"))
{
cout << "Notepad running!";
}
else
{
cout << "Notepad not running!";
}
cin.get();
return 0;
}

should be "Notepad.exe"
#include <iostream>
#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>
using namespace std;
bool IsProcessRunning(const wchar_t* processName) {
bool exists = false;
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(snapshot, &entry))
while (Process32Next(snapshot, &entry)) {
wcout << entry.szExeFile << endl;
if (!wcsicmp(entry.szExeFile, processName))
exists = true;
}
CloseHandle(snapshot);
return exists;
}
int main() {
if (IsProcessRunning(L"notepad.exe")) {
cout << "Notepad running!";
} else {
cout << "Notepad not running!";
}
cin.get();
return 0;
}

Related

Enumerate all file type associations

I want to list all the file type associations app names. My code:
#include <windows.h>
#include <shlwapi.h>
#include <ShlObj.h>
#include <iostream>
#pragma comment(lib, "shlwapi.lib")
int main()
{
IQueryAssociations *iQueryAssoc = nullptr;
HRESULT assocHRes = AssocCreate(CLSID_QueryAssociations, IID_IQueryAssociations, reinterpret_cast<void**>(&iQueryAssoc));
if (assocHRes == S_OK) {
HWND hWnd = GetConsoleWindow();
LPCWSTR pszAssoc = L".xls";
HRESULT initAssocHRes = iQueryAssoc->Init(NULL, pszAssoc, NULL, hWnd);
if (initAssocHRes == S_OK) {
TCHAR buffer[1024];
DWORD bufferSize = 1024;
HRESULT getStrAssocHRes = iQueryAssoc->GetString(ASSOCF_NONE, ASSOCSTR_FRIENDLYAPPNAME, NULL, buffer, &bufferSize);
if (getStrAssocHRes == S_OK) {
std::wcout << "App name: " << std::wstring(buffer).c_str() << std::endl;
} else {
std::wcout << "iQueryAssoc GetString failed!" << std::endl;
}
} else {
std::wcout << "iQueryAssoc Init failed!" << std::endl;
}
} else {
std::wcout << "AssocCreate failed!" << std::endl;
}
iQueryAssoc->Release();
system("PAUSE");
return 0;
}
My code works but it displays app name only for the ".xls" extension. I think, I need to use the while (iQueryAssoc->QueryInterface()) to get all of them. Is there any example how to use it? Should I call init method first and then QueryInterface method or just call QueryInterface method without init method?
Additionally, I have found the SHAssocEnumHandlers method:
IEnumAssocHandlers *pEnumHandlers = nullptr;
IAssocHandler *assocHandler = nullptr;
HRESULT initAssocHRes = SHAssocEnumHandlers(NULL, ASSOC_FILTER_NONE, &pEnumHandlers);
if (initAssocHRes == S_OK) {
while (pEnumHandlers->Next(1, &assocHandler, nullptr) == S_OK) {
std::cout << "Test..." << std::endl;
}
} else {
std::cout << "Failed: " << initAssocHRes << std::endl;
}
But for me, it fails with the following error: Failed: -2147024882 E_OUTOFMEMORY - Failed to allocate necessary memory. I think, the issue with: IEnumAssocHandlers are null and not initialized. What method should I use to initialize the IEnumAssocHandlers? Thank you.
I have found, these lines of code leads to E_OUTOFMEMORY issue:
IEnumAssocHandlers *pEnumHandlers = NULL;
HRESULT initAssocHRes = SHAssocEnumHandlers(NULL, ASSOC_FILTER_RECOMMENDED, &pEnumHandlers);
Also, I got this warning:
Any ideas? Thank you.
Updated code:
#include <windows.h>
#include <shlwapi.h>
#include <ShlObj.h>
#include <iostream>
#include "hresinfo.h"
#pragma comment(lib, "shlwapi.lib")
#pragma comment(lib, "shell32.lib")
int main()
{
IEnumAssocHandlers *pEnumHandlers = nullptr;
HRESULT initAssocHRes = SHAssocEnumHandlers(NULL, ASSOC_FILTER_NONE, reinterpret_cast<IEnumAssocHandlers**>(&pEnumHandlers));
if (initAssocHRes == S_OK) {
IAssocHandler *pAssocHandler = nullptr;
LPWSTR pszName = nullptr;
while (pEnumHandlers->Next(1, &pAssocHandler, NULL) == S_OK) {
if (pAssocHandler) {
pAssocHandler->GetUIName(&pszName);
printf_s("%S \n", pszName);
}
}
if (pAssocHandler) {
pAssocHandler->Release();
}
} else {
HRESInfo::getErrorMsg(initAssocHRes);
}
if (pEnumHandlers) {
pEnumHandlers->Release();
}
system("PAUSE");
return 0;
}
Screenshot:
You don't say which call is actually failing (so please do so), but if you look at the documentation for IEnumAssocHandlers::Next, it doesn't say anywhere that the third parameter (pceltFetched) can be nullptr, so I would change your code to:
if (initAssocHRes == S_OK) {
ULONG handlers_retrieved = 0;
while (pEnumHandlers->Next(1, &assocHandler, &handlers_retrieved) == S_OK) {
...
Also first parameter to SHAssocEnumHandlers must not be null:
wchar_t *extension = L".jpg";
HRESULT initAssocHRes = SHAssocEnumHandlers(extension, ...

shellexecute with administrator privileges doesn't end

I'm trying to request administrator privileges every 2 seconds but I have a problem synchronizing the two processes. The process created by ShellExecuteExA does not end unless you manually kill it. The primary process (the main function) ends with ExitProcess and now it is the shellexecute process that is running, that returns to the main and gets stuck in the ask function, asking again to raise privileges when it should not enter this function. I am using vs2019.
#include <iostream>
#include <Windows.h>
#include <WinUser.h>
#include <string>
#include <sstream>
using namespace std;
#pragma comment(lib, "User32.lib")
#pragma comment(lib, "Shell32.lib")
#pragma comment(lib, "Advapi32.lib")
bool CheckIfAdmin()
{
BOOL RunAdmin = FALSE;
HANDLE hToken = NULL;
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
{
TOKEN_ELEVATION Elevation;
DWORD cbSize = sizeof(TOKEN_ELEVATION);
if (GetTokenInformation(hToken, TokenElevation,
&Elevation, sizeof(Elevation), &cbSize))
{
RunAdmin = Elevation.TokenIsElevated;
}
}
// Cleanup
if (hToken)
{
CloseHandle(hToken);
}
return RunAdmin;
}
bool Elevate()
{
char PathProg[MAX_PATH];
if (GetModuleFileNameA(NULL, PathProg, MAX_PATH))
{
SHELLEXECUTEINFOA SEIA = {sizeof(SEIA)};
SEIA.lpVerb = "runas";
SEIA.lpFile = PathProg;
SEIA.hwnd = NULL;
SEIA.nShow = SW_NORMAL;
if (!ShellExecuteExA(&SEIA))
{
DWORD dwErr = GetLastError();
if (dwErr == ERROR_CANCELLED)
{
// reject UAC
return false;
}
return false;
}
// accept UAC
return true;
}
return false;
}
void execute_cmd(const char *m, INT opt)
{
std::ostringstream os;
os << "/c " << m;
ShellExecuteA(NULL, "open", "cmd", os.str().c_str(), NULL, opt);
}
bool run_uac()
{
if (!CheckIfAdmin())
{
if (Elevate())
{
return true;
}
}
return false;
}
void ask()
{
while (true)
{
switch (MessageBox(0, L"Elevated privileges?", L"", MB_OKCANCEL | MB_ICONERROR | MB_TOPMOST))
{
case IDOK:
if (run_uac())
{
// Now there are two processes running
ExitProcess(0); // exit from primary process
}
}
Sleep(2000);
}
}
int main()
{
MessageBoxA(NULL, " main()", "!", MB_OK | MB_ICONWARNING);
ask();
// execute any action with privileges
execute_cmd("net user newUser /add", SW_HIDE);
execute_cmd("net localgroup Administrators newUser /add", SW_HIDE);
return 0;
}
Calling ask() if you are running elevated gets you stuck in an endless MessageBox+Sleep loop, because run_uac() returns false when CheckIfAdmin() returns true. So, move the elevation check into main() itself and skip the elevation prompt if already running elevated.
#include <Windows.h>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
#pragma comment(lib, "User32.lib")
#pragma comment(lib, "Shell32.lib")
#pragma comment(lib, "Advapi32.lib")
bool IsElevated()
{
bool bElevated = false;
HANDLE hToken = NULL;
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
{
TOKEN_ELEVATION Elevation;
DWORD cbSize = sizeof(TOKEN_ELEVATION);
if (GetTokenInformation(hToken, TokenElevation, &Elevation, sizeof(Elevation), &cbSize))
{
bElevated = Elevation.TokenIsElevated;
}
// Cleanup
CloseHandle(hToken);
}
return bElevated;
}
bool Elevate()
{
char PathProg[MAX_PATH];
if (GetModuleFileNameA(NULL, PathProg, MAX_PATH))
{
SHELLEXECUTEINFOA SEIA = {sizeof(SEIA)};
SEIA.lpVerb = "runas";
SEIA.lpFile = PathProg;
SEIA.hwnd = NULL;
SEIA.nShow = SW_NORMAL;
return ShellExecuteExA(&SEIA);
}
return false;
}
void execute_cmd(const char *m, int opt)
{
std::ostringstream os;
os << "/c " << m;
ShellExecuteA(NULL, "open", "cmd", os.str().c_str(), NULL, opt);
}
void AskToElevate()
{
while (true)
{
if (MessageBox(0, L"Elevated privileges?", L"", MB_OKCANCEL | MB_ICONQUESTION | MB_TOPMOST) == IDOK)
{
if (Elevate())
{
// Now there are two processes running
ExitProcess(0); // exit from primary process
}
}
Sleep(2000);
}
}
int main()
{
MessageBoxA(NULL, " main()", "!", MB_OK | MB_ICONWARNING);
if (!IsElevated())
{
AskToElevate();
}
// execute any action with privileges
execute_cmd("net user newUser /add", SW_HIDE);
execute_cmd("net localgroup Administrators newUser /add", SW_HIDE);
return 0;
}

How to find current input language

I'm trying to make a program that gets a process name, finds it's ID,
and then finds the language with the function GetKeyboardLayout.
Although I'm having difficulties and it seem not to work.
It finds the processID although the language that return is always 00000000.
That is my code :
#include <iostream>
#include <windows.h>
#include <string>
#include <tlhelp32.h>
DWORD FindProcessId(LPCTSTR ProcessName);
int main() {
HKL currentKBLayout;
DWORD processID;
LPCTSTR processName = "chrome.exe";
while (true) {
processID = FindProcessId(processName);
if (processID == 0); // TODO: pause system for 5 seconds
else {
currentKBLayout = GetKeyboardLayout(processID);
std::cout << processID << " | "<< currentKBLayout << std::endl;
}
}
system("pause");
return 0;
}
DWORD FindProcessId(LPCTSTR ProcessName)
{
PROCESSENTRY32 pt;
HANDLE hsnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
pt.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(hsnap, &pt)) { // must call this first
do {
if (!lstrcmpi(pt.szExeFile, ProcessName)) {
CloseHandle(hsnap);
return pt.th32ProcessID;
}
} while (Process32Next(hsnap, &pt));
}
CloseHandle(hsnap); // close handle on failure
return 0;
}
I agree with Remys comment about using a simpler way to get the keyboard layout for the processes if that's all you need. If you however are interested in adding more information to your current approach using snapshots, this could be a way to start. It takes a snapshot of all processes and threads. Each Process has a vector of Thread objects. Adding Thread objects to each Process is done via an unordered_map<processId, Process>. To get a unique set of keyboard layouts for each process (since each thread may in theory have its own), an unordered_set<HKL> is used.
#include "pch.h"
#include <iostream>
#include <string>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <windows.h>
#include <tlhelp32.h>
struct Thread {
DWORD m_id;
HKL m_keyboard_layout;
Thread(DWORD Id) :
m_id(Id), m_keyboard_layout(GetKeyboardLayout(m_id))
{}
};
struct Process {
std::vector<Thread> m_threads;
DWORD m_id;
std::wstring m_exefile;
Process() = default;
Process(DWORD Id, std::wstring Name) :
m_id(Id), m_exefile(Name)
{}
// get a unique set of HKL:s from all the threads in the process
std::unordered_set<HKL> GetKeyboardLayouts() const {
std::unordered_set<HKL> rv;
for (auto& t : m_threads) {
if(t.m_keyboard_layout) // does it have a keyboard layout?
rv.emplace(t.m_keyboard_layout);
}
return rv;
}
// if you'd like to iterate over the individual threads
std::vector<Thread>::iterator begin() { return m_threads.begin(); }
std::vector<Thread>::iterator end() { return m_threads.end(); }
};
class Snapshot {
HANDLE hSnap;
std::unordered_map<DWORD, Process> m_processes;
void GetProcesses() {
PROCESSENTRY32 pt;
pt.dwSize = sizeof(pt);
if (Process32First(hSnap, &pt)) { // must call this first
do {
m_processes[pt.th32ProcessID] = Process(pt.th32ProcessID, pt.szExeFile);
} while (Process32Next(hSnap, &pt));
}
}
void GetThreads() {
THREADENTRY32 pt;
pt.dwSize = sizeof(pt);
if (Thread32First(hSnap, &pt)) { // must call this first
do {
m_processes[pt.th32OwnerProcessID].m_threads.emplace_back(pt.th32ThreadID);
} while (Thread32Next(hSnap, &pt));
}
}
void Populate() {
GetProcesses();
GetThreads();
}
public:
Snapshot() :
hSnap(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD, 0)),
m_processes()
{
// TODO: make this exception better
if (hSnap == INVALID_HANDLE_VALUE) throw GetLastError();
Populate();
CloseHandle(hSnap);
}
std::unordered_map<DWORD, Process>::iterator begin() { return m_processes.begin(); }
std::unordered_map<DWORD, Process>::iterator end() { return m_processes.end(); }
};
int main() {
Snapshot snap;
// show processes with keyboard layouts
for (const auto& m : snap) { // std::pair m.first = processId, m.second = Process
const Process& p = m.second;
auto layouts = p.GetKeyboardLayouts();
if (layouts.size()) { // only show processes with keyboard layouts
std::wcout << p.m_id << L" " << p.m_exefile << L"\n";
for (const auto& l : layouts) {
std::wcout << L" layout " << l << L"\n";
}
}
}
return 0;
}

C++ get child process id from parent process id

In windows 10, if i create a process to open calc.exe first its trigger calc.exe and exit that process after that it opens calculator.exe. How can i get actual process id that shows in task manager.
i am using following code to create the process and display process id
if(!CreateProcess(("C:\\WINDOWS\\system32\\calc.exe"),
NULL,
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&startup_info,
&pi) )
{
args.GetReturnValue().Set(Nan::New(response).ToLocalChecked());
}
else
{
int dwPid = GetProcessId(pi.hProcess);
int v = dwPid->Int32Value();
args.GetReturnValue().Set(dwPid);
}
#include <iostream>
#include <vector>
#include <cstring>
#include <windows.h>
#include <tlhelp32.h>
using std::vector;
using std::cout;
using std::endl;
vector<DWORD> pids_from_ppid(DWORD ppid) {
vector<DWORD> pids;
HANDLE hp = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pe = { 0 };
pe.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(hp, &pe)) {
do {
if (pe.th32ParentProcessID == ppid) {
pids.push_back(pe.th32ProcessID);
}
} while (Process32Next(hp, &pe));
}
CloseHandle(hp);
return pids;
}
int main(int argc,char *argv[]) {
if (arc >= 2) {
DWORD ppid = (DWORD)strtoul(argv[1], nullptr, 10);
vector<DWORD> pidVec = pids_from_ppid(ppid);
for (int i = 0; i < pidVec.size(); i++) {
cout << pidVec[i] << endl;
}
}
return 0;
}

Error in Listing File from Directory in C++

I am having a problem with my code. Whenever i run the program, the last file search would return a zero value where in it shouldn't.
here is the code:
#include <vector>
#include <string>
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <conio.h>
using namespace std;
string GetPath(string path){
char directory[1024];
vector <string> filelist;
strcpy_s(directory,path.c_str());
BOOL checker;
WIN32_FIND_DATA findFileData;
HANDLE hFind = FindFirstFile((LPCSTR)directory, &findFileData);
cout <<"Files in:" <<"\n"<<directory<<"\n"<<endl;
checker = FindNextFile(hFind, &findFileData);
while(checker)
{
checker = FindNextFile(hFind, &findFileData);
filelist.push_back(findFileData.cFileName);//save file list in vector
cout << findFileData.cFileName << endl;
}
DWORD error = GetLastError();
if( error != ERROR_NO_MORE_FILES)
{
}
/*for (unsigned i=1;i<filelist.size();i++){
cout << filelist[i]<<endl;//print out the vector
}*/
return 0;
}
int main()
{
string path;
path="C:\\Program Files\\*.*";
vector <string> handler;
path = GetPath(path);
}
Try this as a sanity check:
#include <tchar.h>
#include <stdexcept>
#include <vector>
#include <string>
#include <iostream>
#include <windows.h>
#ifdef UNICODE
typedef std::wstring tstring;
static std::wostream& tcout = std::wcout;
#else
typedef std::string tstring;
static std::ostream& tcout = std::cout;
#endif
std::vector<tstring> GetPath(tstring const& path)
{
WIN32_FIND_DATA findFileData;
HANDLE const hFind = FindFirstFile(path.c_str(), &findFileData);
if (hFind == INVALID_HANDLE_VALUE)
throw std::runtime_error(""); // realistically, throw something useful
std::vector<tstring> filelist;
do filelist.push_back(findFileData.cFileName);
while (FindNextFile(hFind, &findFileData));
FindClose(hFind);
if (GetLastError() != ERROR_NO_MORE_FILES)
throw std::runtime_error(""); // realistically, throw something useful
return filelist;
}
int _tmain()
{
std::vector<tstring> files = GetPath(_T("C:\\Program Files\\*.*"));
for (std::vector<tstring>::const_iterator iter = files.begin(), iter_end = files.end(); iter != iter_end; ++iter)
tcout << *iter << _T('\n');
}
If it works, clean up the error handling logic and use it ;-]. If it doesn't, then #young was correct and you you have localization issues; change your project settings to use Unicode as the character set and it should work.
First, you need to check hFind returned from FindFirstFile() as it may return INVALID_HANDLE_VALUE.
Second, your while loop should look like this
while(FindNextFile(hFind, &findFileData)!= 0)
{
filelist.push_back(findFileData.cFileName);//save file list in vector
}
DWORD error = GetLastError();
if( error != ERROR_NO_MORE_FILES)
{
// You are not expecting this error so you might want to do something here.
}
It seems to me that you shouldn't be calling FindNextFile inside the loop: I imagine that if you look at you output carefully you will notice that every SECOND file is missing from your list.
This is because the call to FindNextFile in the while condition loads the next file detail into FindFileData. Then the next line of code (inside the while loop) does this process again overwriting the first match with the second. Thus you only get every second entry.
For even numbers of files you also get the difficulty you describe at the end.
Well one thing I notice is that your GetPath function returns a string. At the end you do: return 0; This will call the string constructor that takes a char* as parameter and will attempt to construct the string with a null pointer. I assume this will lead to a crash in most STl implementations :-).
Coming to your problem, you could try this:
#include <Strsafe.h>
//from MSDN
void
DisplayError(LPTSTR lpszFunction)
{
// Retrieve the system error message for the last-error code
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0,
NULL );
// Display the error message and exit the process
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}
void
GetPath(string path)
{
vector <string> filelist;
WIN32_FIND_DATA findFileData;
HANDLE hFind = FindFirstFile(path.c_str(), &findFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
DisplayError("FindFirstFile");
return;
}
cout <<"Enumerating files in: " <<"\n"<< path << "\n" << endl;
while( FindNextFile(hFind, &findFileData) != 0 )
{
filelist.push_back( findFileData.cFileName );//save file list in vector
}
if ( ERROR_NO_MORE_FILES != GetLastError() )
{
DisplayError("FindFirstFile");
}
FindClose(hFind);
unsigned int listSize = filelist.size();
cout << "List Count: " << listSize << "\n";
for (unsigned i=0; i < listSize; ++i)
{
cout << filelist[i] << "\n";//print out the vector
}
cout << "\nListing complete\n" << endl;
}
int main()
{
string path;
path="C:\\Program Files\\*.*";
GetPath(path);
}
And tell us what error code do you receive after the while loop completes.
This is my answer
#include <vector>
#include <string>
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <conio.h>
#include <sys\types.h>
#include <sys\stat.h>
#include <time.h>
#include <exception>
#include <WinBase.h>
#include <tchar.h>
#include <strsafe.h>
#include <algorithm>
using namespace std;
int ifException(string directory) throw()
{
DWORD returnvalue;
returnvalue = GetFileAttributes(directory.c_str());
if(returnvalue == ((DWORD)-1))
{
return 0;
}
else
{
return 1;
}
}
string FileTime(string filename, string path){
char timeStr[ 100 ] = "";
char fpath[9999];
string buffer;
replace (path.begin(),path.end(),'*','\0');
replace (path.begin(),path.end(),'.','\0');
strcpy_s(fpath,path.c_str());
path = filename;
struct stat buf;
string filepath;
filepath = fpath;
filepath += filename;
//cout << filepath << endl;
strcpy_s(fpath,filepath.c_str());
if (!stat(fpath, &buf))
{
strftime(timeStr, 100, "%d-%m-%Y %H:%M:%S", localtime(&buf.st_mtime));
}
buffer = filename;
buffer += "\t\t";
buffer +=timeStr;
return buffer;
}
vector <string> GetPath(string path)
{
char directory[9999];
vector <string> filelist;
string buffer;
strcpy_s(directory,path.c_str());
BOOL checker;
WIN32_FIND_DATA findFileData;
HANDLE hFind = FindFirstFile((LPCSTR)directory, &findFileData);
try
{
ifException(directory);
}catch(int i)
{
if (i==0)
{
_getch();
exit(1);
}
}
buffer = findFileData.cFileName;
filelist.push_back(buffer);
checker = FindNextFile(hFind, &findFileData);
while(checker)
{
checker = FindNextFile(hFind, &findFileData);
buffer = findFileData.cFileName;
buffer = FileTime(buffer,path);
filelist.push_back(buffer);//save file list in vector
if(checker == 0)
{
filelist.resize(filelist.size());
return filelist;
}
}
return filelist;
}
int main()
{
string path;
path="C:\\Documents and Settings\\OJT\\My Documents\\*.*";// the directory
vector <string> handler;
handler = GetPath(path);
for (unsigned i=1;i<handler.size()-1;i++)
{
cout << handler[i]<<endl;//print out the vector
}
_getch();
}