I have the following code (it gets all processes then search for a regex pattern in them, code for a larger personal project for malware detection), the code does what I want but the only problem it is using 100% of CPU, what do I do wrong? Bad memory allocation? I compiled it with MS Visual Studio 2010 (cl.exe /EHsc mycode.cpp)
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>
#include <tlhelp32.h>
#include <psapi.h>
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <iterator>
#include <regex>
using namespace std;
#pragma comment(lib, "psapi.lib")
void PrintProcessNameAndID(DWORD);
void find_locs(HANDLE process);
void ListProcesses();
int main(int argc, char **argv) {
ListProcesses();
}
void find_locs(HANDLE process) {
unsigned char *p = NULL;
MEMORY_BASIC_INFORMATION info;
for ( p = NULL;
VirtualQueryEx(process, p, &info, sizeof(info)) == sizeof(info);
p += info.RegionSize )
{
std::string buffer;
if (info.State == MEM_COMMIT &&
(info.Type == MEM_MAPPED || info.Type == MEM_PRIVATE))
{
DWORD bytes_read;
buffer.resize(info.RegionSize);
ReadProcessMemory(process, p, &buffer[0], info.RegionSize, &bytes_read);
buffer.resize(bytes_read);
const std::tr1::regex rx("([\\w-+]+(?:\\.[\\w-+]+)*#(?:[\\w-]+\\.)+[a-zA-Z]{2,7})");
std::tr1::match_results<std::string::const_iterator> res;
std::tr1::regex_search(buffer, res, rx);
ofstream myfile;
myfile.open ("proc.txt", ios::app);
for (unsigned int i=0; i<res.size(); ++i)
{
std::cout << res[i] << std::endl;
myfile << res[i] << "\n";
}
myfile.close();
}
}
}
void ListProcesses()
{
DWORD aProcesses[1024];
DWORD cbNeeded;
DWORD cProcesses;
unsigned int i;
if (!EnumProcesses(aProcesses,sizeof(aProcesses),&cbNeeded))
return;
cProcesses = cbNeeded / sizeof(DWORD);
for ( i = 0; i < cProcesses; i++ )
{
PrintProcessNameAndID(aProcesses[i]);
}
}
void PrintProcessNameAndID(DWORD processID)
{
TCHAR szProcessName[MAX_PATH]; // = TEXT("<unknown>");
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID);
if (NULL != hProcess)
{
HMODULE hMod;
DWORD cbNeeded;
if (EnumProcessModules(hProcess, &hMod, sizeof(hMod),
&cbNeeded))
{
GetModuleBaseName(hProcess, hMod, szProcessName,
sizeof(szProcessName)/sizeof(TCHAR));
}
}
_tprintf(TEXT("pid: %u file: %s\n"), processID, szProcessName);
find_locs(hProcess);
CloseHandle(hProcess);
}
Thanks for help!
There's nothing wrong with a program taking up 100% of the processor... (I don't know how I can expand this answer beyond this)
Any program running continuosly without a Sleep call (some sort of saying to OS "I'm done for now") will try to run as fast as possible, requesting next iteration of the loop just after the previous one. It takes every available CPU cycle, because you've requested it to do so.
A couple things:
The CPU running at 100% is not too uncommon. This is especially true if you are running computationally intensive tasks (such as prime number computations). Eg:
How to get 100% CPU usage from a C program
Or, what is probably more applicable in your case, is that it's due to a myriad combination of things related to windows itself, your hardware combination and configuration:
http://www.techradar.com/us/news/computing/why-is-my-cpu-running-at-100-710254
In all, it's not something to be too worried about. Generally, that is.
Related
hello guys i tried to make a hwid login for a app. The problem is when i compile all the code i have this error.
Error C2676 binary '==': 'std::basic_string,std::allocator>' does not define this operator or a conversion to a type acceptable to the predefined operator
#include <Windows.h>
#include <iostream>
#include <tchar.h>
#include <intrin.h>
#include <TlHelp32.h>
#include <algorithm>
#include <vector>
using namespace std;
vector<string> serial;
vector<string> windows;
void loadserial()
{
serial.push_back("1731602307");
}
void loadWindows()
{
windows.push_back("29548");
}
int main()
{
TCHAR volumeName[MAX_PATH + 1] = { 0 };
TCHAR fileSystemName[MAX_PATH + 1] = { 0 };
DWORD serialNumber = 0;
DWORD maxComponentLen = 0;
DWORD fileSystemFlags = 0;
if (GetVolumeInformation(
_T("C:\\"),
volumeName,
ARRAYSIZE(volumeName),
&serialNumber,
&maxComponentLen,
&fileSystemFlags,
fileSystemName,
ARRAYSIZE(fileSystemName)))
{
}
int cpuinfo[4] = { 0, 0, 0, 0 };
__cpuid(cpuinfo, 0);
char16_t hash = 0;
char16_t* ptr = (char16_t*)(&cpuinfo[0]);
for (char32_t i = 0; i < 8; i++)
hash += ptr[i];
while (true)
{
if (find(serial.begin(), serial.end(), serialNumber) != serial.end())
{
std::cout << "nice you are in our auth system!!";
}
else
{
std::cout << "you arent in the whitelist ;(";
}
}
return(0);
}
OK, now it's clear
find(serial.begin(), serial.end(), serialNumber)
serial is a vector<string> but serialNumber is a DWORD. You can't use find to look for a DWORD in a vector of strings. I guess you need to convert the DWORD to a string first, or maybe you could change serial to a vector<DWORD>.
And as drescherjm says get into the habit of looking at the output tab for your error messages, it's much more useful than the error list (which for some reason microsoft insist on showing you first).
I am trying to make a program to store the value 500 into the calculator's memory address for the MR (Memory Restore) button on the calculator application.
I know that the address for this integer is
"calc.exe"+00073320 + 0 + C
If I use a program like cheat engine, I can get the current address for the instance of the calculator.exe i'm running, and write to it just fine that way. However, since this is not a static address, I need a way to get the module base address.
I tried using this GetModuleBase function (see code below) to get the Base Address of the calc.exe, but my issue is that I cannot get the base address. The function always returns 0 instead of the correct address.
I debugged it and found that in the GetModuleBase function, it is not even cycling once through the while loop because bModule is returning 0 from the Module32First function.
#include <tchar.h>
#include <windows.h>
#include <TlHelp32.h>
#include <iostream>
#include <Psapi.h>
#include <wchar.h>
#pragma comment( lib, "psapi" )
using namespace std;
DWORD GetModuleBase(LPSTR lpModuleName, DWORD dwProcessId)
{
MODULEENTRY32 lpModuleEntry = {0};
HANDLE hSnapShot = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, dwProcessId );
if(!hSnapShot)
return NULL;
lpModuleEntry.dwSize = sizeof(lpModuleEntry);
BOOL bModule = Module32First( hSnapShot, &lpModuleEntry );
while(bModule)
{
if(!strcmp( lpModuleEntry.szModule, lpModuleName ) )
{
CloseHandle( hSnapShot );
return (DWORD)lpModuleEntry.modBaseAddr;
}
bModule = Module32Next( hSnapShot, &lpModuleEntry );
}
CloseHandle( hSnapShot );
return NULL;
}
int main() {
HWND hWnd = FindWindow(0, "Calculator");
DWORD BaseAddr;
if(hWnd == 0){
MessageBox(0, "Error cannot find window.", "Error", MB_OK|MB_ICONERROR);
} else {
DWORD proccess_ID;
GetWindowThreadProcessId(hWnd, &proccess_ID);
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, proccess_ID);
if(!hProcess){
MessageBox(0, "Could not open the process!", "Error!", MB_OK|MB_ICONERROR);
} else {
int newdata = 500;
BaseAddr = GetModuleBase("calc.exe",proccess_ID);
//GetModuleBase is always returning 0, so I am not getting the correct base address
DWORD newdatasize = sizeof(newdata);
if(WriteProcessMemory(hProcess, (LPVOID)0x002413FC, &newdata, newdatasize, NULL)){
cout << "Memory successfully written." << endl;
} else {
cout << "Memory failed to write." << endl;
}
CloseHandle(hProcess);
}
}
return 0;
}
Summary: I cannot get the correct base address using my GetModuleBase function, and I need to figure out what I am doing wrong so that I can get the correct base address for the "calc.exe" process.
You should read the modules like this:
#include <windows.h>
#include <TlHelp32.h>
#include <iostream>
//You don't have to use this function if you don't want to..
int strcompare(const char* One, const char* Two, bool CaseSensitive)
{
#if defined _WIN32 || defined _WIN64
return CaseSensitive ? strcmp(One, Two) : _stricmp(One, Two);
#else
return CaseSensitive ? strcmp(One, Two) : strcasecmp(One, Two);
#endif
}
//You read module information like this..
MODULEENTRY32 GetModuleInfo(std::uint32_t ProcessID, const char* ModuleName)
{
void* hSnap = nullptr;
MODULEENTRY32 Mod32 = {0};
if ((hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, ProcessID)) == INVALID_HANDLE_VALUE)
return Mod32;
Mod32.dwSize = sizeof(MODULEENTRY32);
while (Module32Next(hSnap, &Mod32))
{
if (!strcompare(ModuleName, Mod32.szModule, false))
{
CloseHandle(hSnap);
return Mod32;
}
}
CloseHandle(hSnap);
return {0};
}
int main()
{
//Change the process ID below..
BYTE* BaseAddr = GetModuleInfo(5172, "calc.exe").modBaseAddr;
std::cout<<"BASE ADDRESS: "<<(void*)BaseAddr<<"\n";
return 0;
}
EDIT: After further investigation, I found that Visual Studio was compiling for an x32 platform but calc.exe is an x64 process..
To get Visual Studio to compile for x64 you need to do the following:
Then click and select "NEW" from the following drop-down menu:
Next in the following drop down, select x64:
Save the settings and rebuild the project and it should work..
I have a probelm :( i wanna make a program wich gives a random number :) i don't want use rand() function :) i wanna make one for me then turn it to a function ;) for educational purpose :)
but i have a problem :( see my code :)
#include <stdio.h>
#include <iostream>
#include <conio.h>
#include <windows.h>
#define MIN 0
#define MAX 99999
using namespace std;
typedef struct _RANDOM_INFO{
DWORD random;
DWORD min;
DWORD max;
} RANDOM_INFO, * LPRANDOM_INFO;
void Error(LPSTR lpErrorMessage){
cout << lpErrorMessage << endl;
exit(EXIT_FAILURE);
}
void GetRandom(LPVOID lpParam){
DWORD dwListSize = 10000, min = 0, max = 99999;
LPDWORD lpRandom = (LPDWORD)lpParam;
LPSTR lpFileSelf, lpKernel, lpNtdll;
HMODULE hFileSelf = NULL, hKernel = NULL, hNtdll = NULL;
hFileSelf = (HMODULE) GetModuleHandle(NULL);
hKernel = (HMODULE) GetModuleHandle("kernel.dll");
hNtdll = (HMODULE) GetModuleHandle("ntdll.dll");
lpFileSelf = (LPSTR) hFileSelf;
lpKernel = (LPSTR) hKernel;
lpNtdll = (LPSTR) hNtdll;
while(1){
DWORD i;
for(i = 0; i <= dwListSize; i++){
*lpRandom = (DWORD)lpFileSelf[i];
}
i = 0;
}
return;
}
int main(int argc, char **argv)
{
DWORD random = 0;
DWORD getRandomThreadId = 0;
HANDLE hGetRandomThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)GetRandom, &random, 0, &getRandomThreadId);
if(hGetRandomThread == INVALID_HANDLE_VALUE)
Error("Cannot make a random list.");
getch();
cout << random << endl;
Sleep(1500);
return 0;
}
The variable should get a value when and print it but i always i get 0 and a windows error can someone tell me why??? and another problem when i try to use the variable hKernel in the GetRandom function i get an error too :( but it works fine whith hFileSelf and hNtdll !!!! is kernel protected from reading???
Note : this is not a random number generation :) its just a way to get a number from the memory when the user click on the enter on his keyboard :), and its not always the same time for all users so its not always the same pointer in memory :) i hope u understand what i want do :) sorry for my bad englush :) just help me to fix the problem :)
Thank u :)
Your GetRandom() function does not have the correct signature for a CreateThread() callback procedure. Try this instead:
#include <stdio.h>
#include <iostream>
#include <conio.h>
#include <windows.h>
#define MIN 0
#define MAX 99999
using namespace std;
typedef struct _RANDOM_INFO
{
DWORD random;
DWORD min;
DWORD max;
} RANDOM_INFO, * LPRANDOM_INFO;
void Error(LPSTR lpErrorMessage)
{
cout << lpErrorMessage << endl;
exit(EXIT_FAILURE);
}
HMODULE hFileSelf = (HMODULE) GetModuleHandle(NULL);
DWORD WINAPI GetRandomThreadProc(LPVOID lpParam)
{
LPDWORD lpRandom = (LPDWORD) lpParam;
DWORD dwListSize = 10000, min = 0, max = 99999;
LPBYTE lpFileSelf = (LPBYTE) hFileSelf;
while (1)
{
for (DWORD i = 0; i <= dwListSize; ++i)
{
*lpRandom = (DWORD) lpFileSelf[i];
}
Sleep(0);
}
return 0;
}
int main(int argc, char **argv)
{
DWORD dwRandom = 0;
DWORD dwRandomThreadId = 0;
HANDLE hGetRandomThread = CreateThread(NULL, 0, &GetRandomThreadProc, &dwRandom, 0, &dwRandomThreadId);
if (hGetRandomThread == INVALID_HANDLE_VALUE)
Error("Cannot make a random list.");
do
{
getch();
cout << dwRandom << endl;
}
while (WaitForSingleObject(hGetRandomThread, 0) == WAIT_TIMEOUT);
CloseHandle(hGetRandomThread);
return 0;
}
i wanna make a program wich gives a random number
What you are doing has nothing to do with random number generation.
This is one way to do it:
Linear Congruential Generator
I've tried this code in C++ on Win7x64 platform with MSVC++, and I got CPU frequency about 2900000 ticks per second.
When I run this program, my stopwatch returns about 10,000,000 tick, which means it take about 4 seconds to process my program, but my program results are ready for me in 1 second (or less) O_o.
Could you please tell me what is wrong in my code?
#include <iostream>
#include "header.h"
#include <fstream>
#include <string>
#include <sstream>
#include <strsafe.h>
#include <direct.h>
#include <string.h>
using namespace std;
#define CV_TO_NANO 1000000000
#define CV_TO_MICRO 1000000
#define CV_TO_MILLI 1000
unsigned __int64 inline GetRDTSC()
{
__asm
{
; Flush the pipeline
XOR eax, eax
CPUID
; Get RDTSC counter in edx:eax
RDTSC
}
}
unsigned __int64 RunTest(TCHAR *AppName, TCHAR *CmdLine);
void main()
{
unsigned __int64 start = 0;
unsigned __int64 stop = 0;
unsigned __int64 freq = 0;
float rps;
ofstream dataFile;
// get processor freq
QueryPerformanceFrequency((LARGE_INTEGER *)&freq);
cout <<"freq (count per second): "<< freq << endl;
// round per second
rps = 1.0/(freq);
cout <<"rps (1/rps): "<< rps << endl;
dataFile.open ("d:/dataC.txt",ios::out );
for(int i = 0;i<200;i++)
{
SetProcessAffinityMask(GetCurrentProcess(),0x0001);
SetThreadAffinityMask(GetCurrentThread(),0x0001);
cout << RunTest(L"D:\\Child\\Child.exe", NULL);
}
getchar();
return;
}
unsigned __int64 RunTest(TCHAR *AppName, TCHAR *CmdLine)
{
unsigned __int64 start = 0;
unsigned __int64 stop = 0;
PROCESS_INFORMATION processInformation;
STARTUPINFO startupInfo;
memset(&processInformation, 0, sizeof(processInformation));
memset(&startupInfo, 0, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
BOOL result;
start = GetRDTSC();
result = ::CreateProcess(AppName, CmdLine, NULL, NULL, FALSE, REALTIME_PRIORITY_CLASS, NULL, NULL, &startupInfo, &processInformation);
stop = GetRDTSC();
getchar();
if (result == 0)
{
wprintf(L"ERROR: CreateProcess failed!");
}
else
{
WaitForSingleObject( processInformation.hProcess, 0 );
CloseHandle( processInformation.hProcess );
CloseHandle( processInformation.hThread );
}
return stop - start;
}
I think you have a misconception here that QueryPerformanceFrequency is telling you something about the speed of your processor - it isn't. QueryPerformanceFrequency retrieves the frequency of the high-resolution performance counter, which is not guaranteed to have any predictable relationship to your CPU clock speed. This value needs to be used in conjunction with QueryPerformanceCounter in order to get quality timing values, not with assembly that directly queries the RDTSC.
Here is an example of how to use the high-frequency timer to time a block of code:
#include <Windows.h>
#include <iostream>
using namespace std;
int main()
{
LARGE_INTEGER li = {};
__int64 freq, start, stop;
QueryPerformanceFrequency(&li);
freq = li.QuadPart;
cout << "Counter Frequency: " << freq << "\n";
QueryPerformanceCounter(&li);
start = li.QuadPart;
for( int i = 0; i < 1000000; ++i )
{
int n = i * rand();
}
QueryPerformanceCounter(&li);
stop = li.QuadPart;
double elapsed_seconds = static_cast<double>(stop-start) / static_cast<double>(freq);
cout << "Elapsed Time: " << elapsed_seconds << " seconds\n";
}
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();
}