﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>C++博客-wy-文章分类-SDK</title><link>http://www.cppblog.com/wy/category/1407.html</link><description /><language>zh-cn</language><lastBuildDate>Thu, 22 May 2008 07:12:47 GMT</lastBuildDate><pubDate>Thu, 22 May 2008 07:12:47 GMT</pubDate><ttl>60</ttl><item><title>Windows服务程序模板</title><link>http://www.cppblog.com/wy/articles/48530.html</link><dc:creator>鱼儿</dc:creator><author>鱼儿</author><pubDate>Wed, 30 Apr 2008 09:25:00 GMT</pubDate><guid>http://www.cppblog.com/wy/articles/48530.html</guid><wfw:comment>http://www.cppblog.com/wy/comments/48530.html</wfw:comment><comments>http://www.cppblog.com/wy/articles/48530.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cppblog.com/wy/comments/commentRss/48530.html</wfw:commentRss><trackback:ping>http://www.cppblog.com/wy/services/trackbacks/48530.html</trackback:ping><description><![CDATA[<p>msdn偶得，感觉是那么的干净漂亮，好东西大家分享<br>&nbsp;<br>&nbsp;<br>&nbsp;<br>/***************************************************************\<br>*&nbsp;&nbsp;&nbsp; TEMPLATE CPP FOR SERVICE PROGRAM 01/08/2003 * <br>*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; BY JONATHAN NG&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; * <br>*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; * <br>*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; * <br>* Usage:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; * <br>* 1) Add service.cpp to project workspace&nbsp;&nbsp;&nbsp;&nbsp; *<br>* 2) Change the ServiceName under the global variable&nbsp; * <br>*&nbsp; to desire name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; *<br>* 3) Add your function into ServiceThread()&nbsp;&nbsp;&nbsp;&nbsp; *<br>* 4) DONE!&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; *<br>*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; *<br>* Install:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; * <br>* 1) Use command prompt.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; *<br>* 2) Locate the exe.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; *<br>* 3) Type &lt;programname&gt; -i&nbsp; Install&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; *<br>*&nbsp; Type &lt;programname&gt; -u&nbsp; Uninstall&nbsp;&nbsp;&nbsp;&nbsp; *<br>*&nbsp; Type &lt;programname&gt; HELP&nbsp; For more&nbsp;&nbsp;&nbsp;&nbsp; *<br>*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; *<br>\***************************************************************/<br>#include &lt;windows.h&gt;<br>#include &lt;iostream.h&gt;<br>#include &lt;stdio.h&gt;<br>static struct ErrEntry {<br>&nbsp;int code;<br>&nbsp;const char* msg;<br>} ErrList[] = {<br>// <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/system_error_codes.asp">http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/system_error_codes.asp</a><br>&nbsp;{ 0, "No error" },<br>&nbsp;{ 1055, "The service database is locked." },<br>&nbsp;{ 1056, "An instance of the service is already running." },<br>&nbsp;{ 1060, "The service does not exist as an installed service." },<br>&nbsp;{ 1061, "The service cannot accept control messages at this time." },<br>&nbsp;{ 1062, "The service has not been started." },<br>&nbsp;{ 1063, "The service process could not connect to the service controller." },<br>&nbsp;{ 1064, "An exception occurred in the service when handling the control request." },<br>&nbsp;{ 1065, "The database specified does not exist." },<br>&nbsp;{ 1066, "The service has returned a service-specific error code." },<br>&nbsp;{ 1067, "The process terminated unexpectedly." },<br>&nbsp;{ 1068, "The dependency service or group failed to start." },<br>&nbsp;{ 1069, "The service did not start due to a logon failure." },<br>&nbsp;{ 1070, "After starting, the service hung in a start-pending state." },<br>&nbsp;{ 1071, "The specified service database lock is invalid." },<br>&nbsp;{ 1072, "The service marked for deletion." },<br>&nbsp;{ 1073, "The service already exists." },<br>&nbsp;{ 1078, "The name is already in use as either a service name or a service display name." },<br>};<br>const int nErrList = sizeof(ErrList) / sizeof(ErrEntry);</p>
<p>//// Global /////////////////////////////////////////////////////////<br>FILE*&nbsp; pLog;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br>char*&nbsp; ServiceName = "ServiceTest";&nbsp; // Name of the service<br>HANDLE&nbsp; terminateEvent = NULL;&nbsp;&nbsp; // Event used to hold ServerMain from completing<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Handle used to communicate status info with <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // the SCM. Created by RegisterServiceCtrlHandler<br>HANDLE&nbsp; threadHandle = 0;&nbsp;&nbsp;&nbsp; // Thread for the actual work<br>BOOL&nbsp; pauseService = FALSE;&nbsp;&nbsp; // Flags holding current state of service<br>BOOL&nbsp; runningService = FALSE;&nbsp;&nbsp; //<br>SERVICE_STATUS_HANDLE serviceStatusHandle; //<br>DWORD WINAPI ServiceThread( LPDWORD lParam);<br>BOOL InitService();<br>BOOL SendStatusToSCM(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwServiceSpecificExitCode, DWORD dwCheckPoint, DWORD dwWaitHint);<br>void ResumeService();<br>void PauseService();<br>void StopService();<br>void terminate(DWORD error);<br>void ServiceCtrlHandler(DWORD controlCode);//服务操作<br>void ServiceMain(DWORD argc, LPTSTR *argv);//注册服务<br>void ErrorHandler(char *s, int err);<br>void GetStatus(SC_HANDLE service);<br>void ShowUsage();<br>// service config program tasks<br>bool InstallService();<br>bool UninstallService();<br>bool GetConfiguration();<br>bool ChangeConfig();<br>// service control program tasks<br>bool ServiceRun();<br>bool ServiceControl(char* CONTROL);<br>void main(int argc, char *argv[])<br>{<br>&nbsp;SERVICE_TABLE_ENTRY serviceTable[] =<br>&nbsp;{<br>&nbsp; { ServiceName, (LPSERVICE_MAIN_FUNCTION) ServiceMain},<br>&nbsp; { NULL, NULL}<br>&nbsp;};<br>&nbsp;BOOL success;<br>&nbsp;<br>&nbsp;if(argc == 2)<br>&nbsp;{<br>&nbsp; if (stricmp("-i", argv[1]) == 0)<br>&nbsp;&nbsp; InstallService();<br>&nbsp; else if (stricmp("-u", argv[1]) == 0)&nbsp;&nbsp; <br>&nbsp;&nbsp; UninstallService();<br>&nbsp; else if (stricmp("-r", argv[1]) == 0)<br>&nbsp;&nbsp; ServiceRun();<br>&nbsp; else if (stricmp("-s", argv[1]) == 0)<br>&nbsp;&nbsp; ServiceControl("STOP");<br>&nbsp; else if (stricmp("-p", argv[1]) == 0)<br>&nbsp;&nbsp; ServiceControl("PAUSE");<br>&nbsp; else if (stricmp("-c", argv[1]) == 0)<br>&nbsp;&nbsp; ServiceControl("RESUME");<br>&nbsp; else if (stricmp("status", argv[1]) == 0)<br>&nbsp; { <br>&nbsp;&nbsp; SC_HANDLE scm, service;<br>&nbsp;&nbsp; //Open connection to SCM<br>&nbsp;&nbsp; scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);<br>&nbsp;&nbsp; if (!scm)<br>&nbsp;&nbsp;&nbsp; ErrorHandler("OpenSCManager", GetLastError());<br>&nbsp;&nbsp; //Get service's handle<br>&nbsp;&nbsp; service = OpenService(scm, ServiceName, SERVICE_ALL_ACCESS);<br>&nbsp;&nbsp; if (!service)<br>&nbsp;&nbsp;&nbsp; ErrorHandler("OpenService", GetLastError());<br>&nbsp;&nbsp; cout &lt;&lt; "STATUS: ";<br>&nbsp;&nbsp; GetStatus(service);<br>&nbsp; }<br>&nbsp; else if (stricmp("config", argv[1]) == 0)<br>&nbsp;&nbsp; GetConfiguration();<br>&nbsp; else if (stricmp("help", argv[1]) == 0)<br>&nbsp;&nbsp; ShowUsage();<br>&nbsp; //add other custom commands here and <br>&nbsp; //update ShowUsage function<br>&nbsp; else<br>&nbsp;&nbsp; ShowUsage();<br>&nbsp;}<br>&nbsp;<br>&nbsp;else <br>&nbsp;{<br>&nbsp; //register with SCM<br>&nbsp; success = StartServiceCtrlDispatcher(serviceTable);<br>&nbsp; if (!success)<br>&nbsp;&nbsp; ErrorHandler("StartServiceCtrlDispatcher",GetLastError());<br>&nbsp;}<br>}</p>
<p>void ServiceMain(DWORD argc, LPTSTR *argv)<br>{<br>&nbsp;BOOL success;<br>&nbsp;//immediately call registration function <br>&nbsp;serviceStatusHandle = RegisterServiceCtrlHandler(ServiceName, (LPHANDLER_FUNCTION)ServiceCtrlHandler);<br>&nbsp;if (!serviceStatusHandle)<br>&nbsp;{<br>&nbsp; terminate(GetLastError());<br>&nbsp; return;<br>&nbsp;}<br>&nbsp;//notify SCM<br>&nbsp;success = SendStatusToSCM(SERVICE_START_PENDING, NO_ERROR, 0 , 1, 5000);<br>&nbsp;if (!success)<br>&nbsp;{ <br>&nbsp; terminate(GetLastError());<br>&nbsp; return;<br>&nbsp;}<br>&nbsp;//create termination event<br>&nbsp;terminateEvent = CreateEvent (0, TRUE, FALSE, 0);<br>&nbsp;if (!terminateEvent)<br>&nbsp;{<br>&nbsp; terminate(GetLastError());<br>&nbsp; return;<br>&nbsp;}<br>&nbsp;//notify SCM<br>&nbsp;success = SendStatusToSCM(SERVICE_START_PENDING, NO_ERROR, 0 , 2, 1000);<br>&nbsp;if (!success)<br>&nbsp;{ <br>&nbsp; terminate(GetLastError());<br>&nbsp; return;<br>&nbsp;}<br>&nbsp;/*<br>&nbsp;//check for startup parameter<br>&nbsp;if (argc == 2)<br>&nbsp; <br>&nbsp;else<br>&nbsp; <br>&nbsp;*/<br>&nbsp;//notify SCM<br>&nbsp;success = SendStatusToSCM(SERVICE_START_PENDING, NO_ERROR, 0 , 3, 5000);<br>&nbsp;if (!success)<br>&nbsp;{ <br>&nbsp; terminate(GetLastError());<br>&nbsp; return;<br>&nbsp;}<br>&nbsp;//start service<br>&nbsp;success = InitService();<br>&nbsp;if (!success)<br>&nbsp;{ <br>&nbsp; terminate(GetLastError());<br>&nbsp; return;<br>&nbsp;}<br>&nbsp;//notify SCM service is runnning<br>&nbsp;success = SendStatusToSCM(SERVICE_RUNNING, NO_ERROR, 0 , 0, 0);<br>&nbsp;if (!success)<br>&nbsp;{ <br>&nbsp; terminate(GetLastError());<br>&nbsp; return;<br>&nbsp;}<br>&nbsp;//wait for stop signal and then terminate<br>&nbsp;WaitForSingleObject(terminateEvent, INFINITE);<br>&nbsp;terminate(0);<br>}</p>
<p>DWORD WINAPI ServiceThread(LPDWORD lParam)<br>{<br>&nbsp;<br>&nbsp;//DO YOUR THINGS HERE<br>&nbsp;return 0;<br>}<br>//initialises the service by starting its thread<br>BOOL InitService()<br>{<br>&nbsp;DWORD id;<br>&nbsp;// Start the service's thread<br>&nbsp;threadHandle = CreateThread(<br>&nbsp;NULL,<br>&nbsp;0,<br>&nbsp;(LPTHREAD_START_ROUTINE) ServiceThread,<br>&nbsp;NULL,<br>&nbsp;0,<br>&nbsp;&amp;id);<br>&nbsp;<br>&nbsp;if (threadHandle == 0)<br>&nbsp; return FALSE;<br>&nbsp;else<br>&nbsp;{<br>&nbsp; runningService = TRUE;<br>&nbsp; return TRUE;<br>&nbsp;}<br>}<br>//resumes paused service<br>void ResumeService()<br>{<br>&nbsp;pauseService = FALSE;<br>&nbsp;ResumeThread(threadHandle);<br>}<br>//pauses service<br>void PauseService()<br>{<br>&nbsp;pauseService = TRUE;<br>&nbsp;SuspendThread(threadHandle);<br>}<br>//stops service by allowing ServiceMain to complete<br>void StopService()<br>{<br>&nbsp;runningService = FALSE;<br>&nbsp;//set the event that is holding ServiceMain<br>&nbsp;SetEvent(terminateEvent);<br>}<br>//this function consolidates the activities of updating<br>//the service status with SetServiceStatus<br>BOOL SendStatusToSCM(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwServiceSpecificExitCode, DWORD dwCheckPoint, DWORD dwWaitHint)<br>{<br>&nbsp;BOOL success;<br>&nbsp;SERVICE_STATUS serviceStatus;<br>&nbsp;//fill in all of the SERVICE_STATUS fields<br>&nbsp;serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;<br>&nbsp;serviceStatus.dwCurrentState = dwCurrentState;<br>&nbsp;//if in the process of something, then accept<br>&nbsp;//no control events, else accept anything<br>&nbsp;if (dwCurrentState == SERVICE_START_PENDING)<br>&nbsp; serviceStatus.dwControlsAccepted = 0;<br>&nbsp;else<br>&nbsp; serviceStatus.dwControlsAccepted = <br>&nbsp;&nbsp; SERVICE_ACCEPT_STOP | <br>&nbsp;&nbsp; SERVICE_ACCEPT_PAUSE_CONTINUE |<br>&nbsp;&nbsp; SERVICE_ACCEPT_SHUTDOWN;<br>&nbsp;//if a specific exit code is defines, set up the win32 exit code properly<br>&nbsp;if (dwServiceSpecificExitCode == 0)<br>&nbsp; serviceStatus.dwWin32ExitCode = dwWin32ExitCode;<br>&nbsp;else<br>&nbsp; serviceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;<br>&nbsp;<br>&nbsp;serviceStatus.dwServiceSpecificExitCode = dwServiceSpecificExitCode;<br>&nbsp;serviceStatus.dwCheckPoint = dwCheckPoint;<br>&nbsp;serviceStatus.dwWaitHint = dwWaitHint;<br>&nbsp;<br>&nbsp;success = SetServiceStatus (serviceStatusHandle, &amp;serviceStatus);<br>&nbsp;if (!success)<br>&nbsp; StopService();<br>&nbsp;return success;<br>}<br>void ServiceCtrlHandler(DWORD controlCode)<br>{<br>&nbsp;DWORD currentState = 0;<br>&nbsp;BOOL success;<br>&nbsp;switch(controlCode)<br>&nbsp;{<br>&nbsp; // START = ServiceMain()<br>&nbsp; // STOP<br>&nbsp; case SERVICE_CONTROL_STOP:<br>&nbsp;&nbsp; currentState = SERVICE_STOP_PENDING;<br>&nbsp;&nbsp; //notify SCM<br>&nbsp;&nbsp; success = SendStatusToSCM(<br>&nbsp;&nbsp;&nbsp; SERVICE_STOP_PENDING,<br>&nbsp;&nbsp;&nbsp; NO_ERROR,<br>&nbsp;&nbsp;&nbsp; 0,<br>&nbsp;&nbsp;&nbsp; 1,<br>&nbsp;&nbsp;&nbsp; 5000);<br>&nbsp;&nbsp; //stop service<br>&nbsp;&nbsp; StopService();<br>&nbsp;&nbsp; return;<br>&nbsp; // PAUSE<br>&nbsp; case SERVICE_CONTROL_PAUSE:<br>&nbsp;&nbsp; if (runningService &amp;&amp; !pauseService)<br>&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp; //notify SCM<br>&nbsp;&nbsp;&nbsp; success = SendStatusToSCM(<br>&nbsp;&nbsp;&nbsp;&nbsp; SERVICE_PAUSE_PENDING,<br>&nbsp;&nbsp;&nbsp;&nbsp; NO_ERROR,<br>&nbsp;&nbsp;&nbsp;&nbsp; 0,<br>&nbsp;&nbsp;&nbsp;&nbsp; 1,<br>&nbsp;&nbsp;&nbsp;&nbsp; 1000);<br>&nbsp;&nbsp;&nbsp; <br>&nbsp;&nbsp;&nbsp; PauseService();<br>&nbsp;&nbsp;&nbsp; currentState = SERVICE_PAUSED;<br>&nbsp;&nbsp; }<br>&nbsp;&nbsp; break;<br>&nbsp;&nbsp; <br>&nbsp; // RESUME<br>&nbsp; case SERVICE_CONTROL_CONTINUE:<br>&nbsp;&nbsp; if (runningService &amp;&amp; pauseService)<br>&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp; //notify SCM<br>&nbsp;&nbsp;&nbsp; success = SendStatusToSCM(<br>&nbsp;&nbsp;&nbsp;&nbsp; SERVICE_CONTINUE_PENDING,<br>&nbsp;&nbsp;&nbsp;&nbsp; NO_ERROR,<br>&nbsp;&nbsp;&nbsp;&nbsp; 0,<br>&nbsp;&nbsp;&nbsp;&nbsp; 1,<br>&nbsp;&nbsp;&nbsp;&nbsp; 1000);<br>&nbsp;&nbsp;&nbsp; <br>&nbsp;&nbsp;&nbsp; ResumeService();<br>&nbsp;&nbsp;&nbsp; currentState = SERVICE_RUNNING;<br>&nbsp;&nbsp; }<br>&nbsp;&nbsp; break;<br>&nbsp; // UPDATE<br>&nbsp; case SERVICE_CONTROL_INTERROGATE:<br>&nbsp;&nbsp; //update status out of switch()<br>&nbsp;&nbsp; break;<br>&nbsp;&nbsp; <br>&nbsp; case SERVICE_CONTROL_SHUTDOWN:<br>&nbsp;&nbsp; //do nothing<br>&nbsp;&nbsp; return;<br>&nbsp; default:<br>&nbsp;&nbsp; break;<br>&nbsp;}<br>&nbsp;//notify SCM current state<br>&nbsp;SendStatusToSCM(currentState, NO_ERROR, 0, 0, 0);<br>}<br>&nbsp;<br>//handle an error from ServiceMain by cleaning up and tell SCM service didn't start.<br>void terminate(DWORD error)<br>{<br>&nbsp;//close event handle<br>&nbsp;if (terminateEvent)<br>&nbsp; CloseHandle(terminateEvent);<br>&nbsp;//notify SCM service stopped<br>&nbsp;if (serviceStatusHandle)<br>&nbsp; SendStatusToSCM(SERVICE_STOPPED, error, 0, 0, 0);<br>&nbsp;//close thread handle<br>&nbsp;if (threadHandle)<br>&nbsp; CloseHandle(threadHandle);<br>}<br>&nbsp;<br>void ErrorHandler(char *s, int err)<br>{<br>&nbsp;cout &lt;&lt; s &lt;&lt; " failed" &lt;&lt; endl;<br>&nbsp;cout &lt;&lt; "Error (" &lt;&lt; err &lt;&lt; "): ";<br>&nbsp;int i;<br>&nbsp;for (i = 0; i &lt; nErrList; ++i) {<br>&nbsp; if (ErrList[i].code == err) {<br>&nbsp;&nbsp; cout &lt;&lt; ErrList[i].msg;<br>&nbsp;&nbsp; break;<br>&nbsp; }<br>&nbsp;}<br>&nbsp;if (i == nErrList) {<br>&nbsp; cout &lt;&lt; "unknown error";<br>&nbsp;}<br>&nbsp;cout &lt;&lt; endl;<br>&nbsp;pLog = fopen("server.log","a");<br>&nbsp;fprintf(pLog, "%s failed, error code = %d\n",s , err); <br>&nbsp;fclose(pLog);<br>&nbsp;ExitProcess(err);<br>}<br>void ShowUsage()<br>{<br>&nbsp; cout &lt;&lt; endl;<br>&nbsp; cout &lt;&lt; "USAGE:" &lt;&lt; endl;<br>&nbsp; cout &lt;&lt; "server -i\tInstall service" &lt;&lt; endl;<br>&nbsp; cout &lt;&lt; "server -u\tUninstall service" &lt;&lt; endl;<br>&nbsp; cout &lt;&lt; "server -r\tRun service" &lt;&lt; endl;<br>&nbsp; cout &lt;&lt; "server -s\tStop service" &lt;&lt; endl;<br>&nbsp; cout &lt;&lt; "server -p\tPause service" &lt;&lt; endl;<br>&nbsp; cout &lt;&lt; "server -c\tResume service" &lt;&lt; endl;<br>&nbsp; cout &lt;&lt; "server status\tCurrent status" &lt;&lt; endl;<br>&nbsp; cout &lt;&lt; endl;<br>}</p>
<p>////////////////////////////////////////////////////////////////////////////////<br>// Purpose :Install service into SCM.<br>// Parameter:N/A<br>// Returns :N/A<br>////////////////////////////////////////////////////////////////////////////////<br>bool InstallService()<br>{<br>&nbsp;SC_HANDLE newService;<br>&nbsp;SC_HANDLE scm; <br>&nbsp;&nbsp;&nbsp; char szBuffer[255];<br>&nbsp;&nbsp;&nbsp; char szPath[MAX_PATH];<br>&nbsp;//get file path<br>&nbsp;GetModuleFileName( GetModuleHandle(NULL), szPath, MAX_PATH );<br>&nbsp;&nbsp;&nbsp; strcpy( szBuffer, "\"" );<br>&nbsp;&nbsp;&nbsp; strcat( szBuffer, szPath );<br>&nbsp;&nbsp;&nbsp; strcat( szBuffer, "\"" );<br>&nbsp;//open connection to SCM<br>&nbsp;scm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);<br>&nbsp;if (!scm)<br>&nbsp; ErrorHandler("OpenSCManager", GetLastError());<br>&nbsp;//install service<br>&nbsp;newService = CreateService(<br>&nbsp; scm,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //scm database<br>&nbsp; ServiceName,&nbsp;&nbsp;&nbsp; //service name<br>&nbsp; ServiceName,&nbsp;&nbsp;&nbsp; //display name<br>&nbsp; SERVICE_ALL_ACCESS,&nbsp;&nbsp; //access rights to the service<br>&nbsp; SERVICE_WIN32_OWN_PROCESS, //service type<br>&nbsp; SERVICE_AUTO_START,&nbsp;&nbsp; //service start type<br>&nbsp; SERVICE_ERROR_NORMAL,&nbsp; //error control type<br>&nbsp; szBuffer,&nbsp;&nbsp;&nbsp;&nbsp; //service path<br>&nbsp; NULL,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //no load ordering group <br>&nbsp; NULL,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //no tag identifier<br>&nbsp; NULL,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //no dependencies <br>&nbsp; NULL,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //LocalSystem account<br>&nbsp; NULL);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //no password<br>&nbsp;if(!newService)<br>&nbsp;{<br>&nbsp; ErrorHandler("CreateService", GetLastError());<br>&nbsp; return false;<br>&nbsp;}<br>&nbsp;else<br>&nbsp;{<br>&nbsp; cout &lt;&lt; "Service Installed" &lt;&lt; endl;<br>&nbsp; ServiceRun();<br>&nbsp;}<br>&nbsp;//clean up<br>&nbsp;CloseServiceHandle(newService);<br>&nbsp;CloseServiceHandle(scm);<br>&nbsp;<br>&nbsp;return true;<br>}<br>////////////////////////////////////////////////////////////////////////////////<br>// Purpose :Uninstall service from SCM.<br>// Parameter:N/A<br>// Returns :N/A<br>////////////////////////////////////////////////////////////////////////////////<br>bool UninstallService()<br>{<br>&nbsp;SC_HANDLE service;<br>&nbsp;SC_HANDLE scm;<br>&nbsp;BOOL SUCCESS;<br>&nbsp;SERVICE_STATUS status;<br>&nbsp;//Open connection to SCM<br>&nbsp;scm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);<br>&nbsp;if (!scm)<br>&nbsp; ErrorHandler("OpenSCManager", GetLastError());<br>&nbsp;//Get service's handle<br>&nbsp;service = OpenService(scm, ServiceName, SERVICE_ALL_ACCESS | DELETE);<br>&nbsp;if (!service)<br>&nbsp; ErrorHandler("OpenService", GetLastError());<br>&nbsp;//Get service status<br>&nbsp;SUCCESS = QueryServiceStatus(service, &amp;status);<br>&nbsp;if (!SUCCESS)<br>&nbsp; ErrorHandler("QueryServiceStatus", GetLastError());<br>&nbsp;<br>&nbsp;//Stop service if necessary&nbsp; <br>&nbsp;if (status.dwCurrentState != SERVICE_STOPPED)<br>&nbsp;{<br>&nbsp; cout &lt;&lt; "Stopping service..." &lt;&lt; endl;<br>&nbsp; SUCCESS = ControlService(service, SERVICE_CONTROL_STOP, &amp;status);<br>&nbsp; if (!SUCCESS)<br>&nbsp;&nbsp; ErrorHandler("ControlService", GetLastError());<br>&nbsp; Sleep(500);<br>&nbsp;}<br>&nbsp;//Delete service<br>&nbsp;SUCCESS = DeleteService(service);<br>&nbsp;if (SUCCESS)<br>&nbsp; cout &lt;&lt; "Service Uninstalled" &lt;&lt; endl;<br>&nbsp;else<br>&nbsp; ErrorHandler("DeleteService", GetLastError());<br>&nbsp;//Clean up<br>&nbsp;CloseServiceHandle(service);<br>&nbsp;CloseServiceHandle(scm);<br>&nbsp;return true;<br>}</p>
<p>////////////////////////////////////////////////////////////////////////////////<br>// Purpose :Run service<br>// Parameter:N/A<br>// Returns :N/A<br>////////////////////////////////////////////////////////////////////////////////<br>bool ServiceRun() <br>{ <br>&nbsp;&nbsp;&nbsp; SC_HANDLE scm, Service;<br>&nbsp;SERVICE_STATUS ssStatus; <br>&nbsp;&nbsp;&nbsp; DWORD dwOldCheckPoint; <br>&nbsp;&nbsp;&nbsp; DWORD dwStartTickCount;<br>&nbsp;&nbsp;&nbsp; DWORD dwWaitTime;<br>&nbsp;&nbsp;&nbsp; DWORD dwStatus;<br>&nbsp; <br>&nbsp;//open connection to SCM<br>&nbsp;scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);<br>&nbsp;if (!scm)<br>&nbsp; ErrorHandler("OpenSCManager", GetLastError());<br>&nbsp;//open service<br>&nbsp;Service = OpenService(scm, ServiceName, SERVICE_ALL_ACCESS);<br>&nbsp;if(!Service)<br>&nbsp;{<br>&nbsp; ErrorHandler("OpenService", GetLastError());<br>&nbsp; return false;<br>&nbsp;}<br>&nbsp;else<br>&nbsp;{<br>&nbsp; //start service<br>&nbsp; StartService(Service, 0, NULL);<br>&nbsp; GetStatus(Service);<br>&nbsp; // Check the status until the service is no longer start pending. <br>&nbsp; if (!QueryServiceStatus( Service, &amp;ssStatus) )<br>&nbsp;&nbsp; ErrorHandler("QueryServiceStatus", GetLastError());<br>&nbsp; // Save the tick count and initial checkpoint.<br>&nbsp; dwStartTickCount = GetTickCount();<br>&nbsp; dwOldCheckPoint = ssStatus.dwCheckPoint;<br>&nbsp; while (ssStatus.dwCurrentState == SERVICE_START_PENDING) <br>&nbsp; { <br>&nbsp;&nbsp; // Do not wait longer than the wait hint. A good interval is <br>&nbsp;&nbsp; // one tenth the wait hint, but no less than 1 second and no <br>&nbsp;&nbsp; // more than 10 seconds. <br>&nbsp;&nbsp; dwWaitTime = ssStatus.dwWaitHint / 10;<br>&nbsp;&nbsp; if( dwWaitTime &lt; 1000 )<br>&nbsp;&nbsp;&nbsp; dwWaitTime = 1000;<br>&nbsp;&nbsp; else if ( dwWaitTime &gt; 10000 )<br>&nbsp;&nbsp;&nbsp; dwWaitTime = 10000;<br>&nbsp;&nbsp; Sleep( dwWaitTime );<br>&nbsp;&nbsp; // Check the status again. <br>&nbsp;&nbsp; if (!QueryServiceStatus(Service, &amp;ssStatus) )<br>&nbsp;&nbsp;&nbsp; break; <br>&nbsp;&nbsp; if ( ssStatus.dwCheckPoint &gt; dwOldCheckPoint )<br>&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp; // The service is making progress.<br>&nbsp;&nbsp;&nbsp; dwStartTickCount = GetTickCount();<br>&nbsp;&nbsp;&nbsp; dwOldCheckPoint = ssStatus.dwCheckPoint;<br>&nbsp;&nbsp; }<br>&nbsp;&nbsp; else<br>&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp; if(GetTickCount()-dwStartTickCount &gt; ssStatus.dwWaitHint)<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp; // No progress made within the wait hint<br>&nbsp;&nbsp;&nbsp;&nbsp; break;<br>&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp; }<br>&nbsp; }<br>&nbsp; <br>&nbsp; if (ssStatus.dwCurrentState == SERVICE_RUNNING) <br>&nbsp; {<br>&nbsp;&nbsp; GetStatus(Service);<br>&nbsp;&nbsp; dwStatus = NO_ERROR;<br>&nbsp; }<br>&nbsp; else <br>&nbsp; { <br>&nbsp;&nbsp; cout &lt;&lt; "\nService not started." &lt;&lt; endl;<br>&nbsp;&nbsp; cout &lt;&lt; "&nbsp; Current State: " &lt;&lt; ssStatus.dwCurrentState &lt;&lt; endl; <br>&nbsp;&nbsp; cout &lt;&lt; "&nbsp; Exit Code: " &lt;&lt; ssStatus.dwWin32ExitCode &lt;&lt; endl; <br>&nbsp;&nbsp; cout &lt;&lt; "&nbsp; Service Specific Exit Code: " &lt;&lt; ssStatus.dwServiceSpecificExitCode &lt;&lt; endl; <br>&nbsp;&nbsp; cout &lt;&lt; "&nbsp; Check Point: " &lt;&lt; ssStatus.dwCheckPoint &lt;&lt; endl; <br>&nbsp;&nbsp; cout &lt;&lt; "&nbsp; Wait Hint: " &lt;&lt; ssStatus.dwWaitHint &lt;&lt; endl;<br>&nbsp;&nbsp; dwStatus = GetLastError();<br>&nbsp; }&nbsp; <br>&nbsp;}<br>&nbsp;CloseServiceHandle(scm);<br>&nbsp;&nbsp;&nbsp; CloseServiceHandle(Service); <br>&nbsp;&nbsp;&nbsp; return true;<br>}</p>
<p>////////////////////////////////////////////////////////////////////////////////<br>// Purpose :Control service (STOP, PAUSE, CONTINUE).<br>// Parameter:N/A<br>// Returns :N/A<br>////////////////////////////////////////////////////////////////////////////////<br>bool ServiceControl(char* CONTROL)<br>{<br>&nbsp;SC_HANDLE service;<br>&nbsp;SC_HANDLE scm;<br>&nbsp;BOOL SUCCESS;<br>&nbsp;SERVICE_STATUS status;<br>&nbsp;//Open connection to SCM<br>&nbsp;scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);<br>&nbsp;if (!scm)<br>&nbsp; ErrorHandler("OpenSCManager", GetLastError());<br>&nbsp;//Get service's handle<br>&nbsp;service = OpenService(scm, ServiceName, SERVICE_ALL_ACCESS);<br>&nbsp;if (!service)<br>&nbsp; ErrorHandler("OpenService", GetLastError());<br>&nbsp;<br>&nbsp;//stop the service<br>&nbsp;if (stricmp(CONTROL, "STOP") == 0)<br>&nbsp;{<br>&nbsp; cout &lt;&lt; "Service is stopping..." &lt;&lt; endl;<br>&nbsp; SUCCESS = ControlService(service, SERVICE_CONTROL_STOP, &amp;status);<br>&nbsp;}<br>&nbsp;//pause the service<br>&nbsp;else if (stricmp(CONTROL, "PAUSE") == 0)<br>&nbsp;{<br>&nbsp; cout &lt;&lt; "Service is pausing..." &lt;&lt; endl;<br>&nbsp; SUCCESS = ControlService(service, SERVICE_CONTROL_PAUSE, &amp;status);<br>&nbsp;}<br>&nbsp;//continue the service<br>&nbsp;else if (stricmp(CONTROL, "RESUME") == 0)<br>&nbsp;{<br>&nbsp; cout &lt;&lt; "Service is resuming..." &lt;&lt; endl;<br>&nbsp; SUCCESS = ControlService(service, SERVICE_CONTROL_CONTINUE, &amp;status);<br>&nbsp;}<br>&nbsp;if (!SUCCESS)<br>&nbsp; ErrorHandler("ControlService", GetLastError());<br>&nbsp;else<br>&nbsp; GetStatus(service);<br>&nbsp;//Clean up<br>&nbsp;CloseServiceHandle(service);<br>&nbsp;CloseServiceHandle(scm);<br>&nbsp;return true;<br>}</p>
<p>////////////////////////////////////////////////////////////////////////////////<br>// Purpose :Get the current status of the service<br>// Parameter:service handle.<br>// Returns :N/A<br>////////////////////////////////////////////////////////////////////////////////<br>void GetStatus(SC_HANDLE service)<br>{<br>&nbsp;BOOL SUCCESS;<br>&nbsp;SERVICE_STATUS status; <br>&nbsp;DWORD CurrentState;<br>&nbsp;SUCCESS = QueryServiceStatus(service, &amp;status);<br>&nbsp;<br>&nbsp;switch(status.dwCurrentState)<br>&nbsp;{<br>&nbsp; case SERVICE_RUNNING:<br>&nbsp;&nbsp; CurrentState = SERVICE_RUNNING;<br>&nbsp;&nbsp; cout &lt;&lt; "Service RUNNING." &lt;&lt; endl;<br>&nbsp;&nbsp; break;<br>&nbsp; case SERVICE_STOPPED:<br>&nbsp;&nbsp; CurrentState = SERVICE_STOPPED;<br>&nbsp;&nbsp; cout &lt;&lt; "Service STOPPED." &lt;&lt; endl;<br>&nbsp;&nbsp; break;<br>&nbsp; case SERVICE_PAUSED:<br>&nbsp;&nbsp; CurrentState = SERVICE_PAUSED;<br>&nbsp;&nbsp; cout &lt;&lt; "Service PAUSED." &lt;&lt; endl;<br>&nbsp;&nbsp; break;<br>&nbsp; case SERVICE_CONTINUE_PENDING:<br>&nbsp;&nbsp; CurrentState = SERVICE_CONTINUE_PENDING;<br>&nbsp;&nbsp; cout &lt;&lt; "Service is resuming..." &lt;&lt; endl;<br>&nbsp;&nbsp; break;<br>&nbsp; case SERVICE_PAUSE_PENDING:<br>&nbsp;&nbsp; CurrentState = SERVICE_PAUSE_PENDING;<br>&nbsp;&nbsp; cout &lt;&lt; "Service is pausing..." &lt;&lt; endl;<br>&nbsp;&nbsp; break;<br>&nbsp; case SERVICE_START_PENDING:<br>&nbsp;&nbsp; CurrentState = SERVICE_START_PENDING;<br>&nbsp;&nbsp; cout &lt;&lt; "Service is starting..." &lt;&lt; endl;<br>&nbsp;&nbsp; break;<br>&nbsp; case SERVICE_STOP_PENDING:<br>&nbsp;&nbsp; CurrentState = SERVICE_STOP_PENDING;<br>&nbsp;&nbsp; cout &lt;&lt; "Service is stopping..." &lt;&lt; endl;<br>&nbsp;&nbsp; break;<br>&nbsp; default:<br>&nbsp;&nbsp; break;<br>&nbsp;}<br>&nbsp;SendStatusToSCM(CurrentState, NO_ERROR, 0, 0, 0);<br>}<br>////////////////////////////////////////////////////////////////////////////////<br>// Purpose :Get configuration of service<br>// Parameter:N/A<br>// Returns :N/A<br>////////////////////////////////////////////////////////////////////////////////<br>bool GetConfiguration()<br>{<br>&nbsp;SC_HANDLE service;<br>&nbsp;SC_HANDLE scm;<br>&nbsp;BOOL success;<br>&nbsp;LPQUERY_SERVICE_CONFIG buffer;<br>&nbsp;DWORD sizeNeeded;<br>&nbsp;//open connection to SCM<br>&nbsp;scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);<br>&nbsp;if (!scm)<br>&nbsp; ErrorHandler("OpenSCManager", GetLastError());<br>&nbsp;//get service's handle<br>&nbsp;service = OpenService(scm, ServiceName, SERVICE_QUERY_CONFIG);<br>&nbsp;if (!service)<br>&nbsp; ErrorHandler("OpenService", GetLastError());<br>&nbsp; //allocate space for buffer<br>&nbsp;buffer = (LPQUERY_SERVICE_CONFIG)LocalAlloc(LPTR, 4096);<br>&nbsp;&nbsp;&nbsp; // Get the configuration information. <br>&nbsp;success = QueryServiceConfig(service, buffer, 4096, &amp;sizeNeeded);<br>&nbsp;if (!success)<br>&nbsp; ErrorHandler("QueryServiceConfig", GetLastError());<br>&nbsp;//display the info<br>&nbsp;cout &lt;&lt; "Service name\t: " &lt;&lt; buffer-&gt;lpDisplayName &lt;&lt; endl;<br>&nbsp;cout &lt;&lt; "Service type\t: " &lt;&lt; buffer-&gt;dwServiceType &lt;&lt; endl;<br>&nbsp;cout &lt;&lt; "Start type\t: " &lt;&lt; buffer-&gt;dwStartType &lt;&lt; endl;<br>&nbsp;cout &lt;&lt; "Start name\t: " &lt;&lt; buffer-&gt;lpServiceStartName &lt;&lt; endl;<br>&nbsp;cout &lt;&lt; "Path\t\t: " &lt;&lt; buffer-&gt;lpBinaryPathName &lt;&lt; endl;<br>&nbsp;LocalFree(buffer);<br>&nbsp;CloseServiceHandle(service);<br>&nbsp;CloseServiceHandle(scm);<br>&nbsp;return TRUE;<br>}</p>
<p>bool ChangeConfig()<br>{<br>&nbsp;SC_HANDLE service;<br>&nbsp;SC_HANDLE scm;<br>&nbsp;BOOL success;<br>&nbsp;SC_LOCK lock;<br>&nbsp;//open connection to SCM<br>&nbsp;scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS | GENERIC_WRITE);<br>&nbsp;if (!scm)<br>&nbsp; ErrorHandler("OpenSCManager", GetLastError());<br>&nbsp;//lock the database to guarantee exclusive access<br>&nbsp;lock = LockServiceDatabase(scm);<br>&nbsp;if (lock == 0)<br>&nbsp; ErrorHandler("LockServiceDatabase", GetLastError());<br>&nbsp; <br>&nbsp;//get service's handle<br>&nbsp;service = OpenService(scm, ServiceName, SERVICE_ALL_ACCESS);<br>&nbsp;if (!service)<br>&nbsp; ErrorHandler("OpenService", GetLastError());<br>&nbsp;<br>// serviceType = SERVICE_NO_CHANGE;<br>// serviceStart = SERVICE_NO_CHANGE;<br>// serviceError = SERVICE_NO_CHANGE;<br>// path = 0;<br>&nbsp;//change service config<br>&nbsp;success = ChangeServiceConfig(<br>&nbsp; service,<br>&nbsp; SERVICE_NO_CHANGE,<br>&nbsp; SERVICE_NO_CHANGE,<br>&nbsp; SERVICE_NO_CHANGE,<br>&nbsp; NULL,<br>&nbsp; NULL,<br>&nbsp; NULL,<br>&nbsp; NULL,<br>&nbsp; NULL,<br>&nbsp; NULL,<br>&nbsp; NULL);<br>&nbsp;if (!success)<br>&nbsp;{<br>&nbsp; UnlockServiceDatabase(lock);<br>&nbsp; ErrorHandler("ChangeServiceConfig", GetLastError());<br>&nbsp;}<br>&nbsp;//unlock database<br>&nbsp;success = UnlockServiceDatabase(lock);<br>&nbsp;if (!success)<br>&nbsp; ErrorHandler("UnlockServiceDatabase", GetLastError());<br>&nbsp;<br>&nbsp;//clean up<br>&nbsp;CloseServiceHandle(service);<br>&nbsp;CloseServiceHandle(scm);<br>&nbsp;return TRUE;<br>}</p>
<img src ="http://www.cppblog.com/wy/aggbug/48530.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cppblog.com/wy/" target="_blank">鱼儿</a> 2008-04-30 17:25 <a href="http://www.cppblog.com/wy/articles/48530.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>How to search for files in a directory and subdirectories? </title><link>http://www.cppblog.com/wy/articles/5404.html</link><dc:creator>鱼儿</dc:creator><author>鱼儿</author><pubDate>Wed, 12 Apr 2006 08:57:00 GMT</pubDate><guid>http://www.cppblog.com/wy/articles/5404.html</guid><wfw:comment>http://www.cppblog.com/wy/comments/5404.html</wfw:comment><comments>http://www.cppblog.com/wy/articles/5404.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cppblog.com/wy/comments/commentRss/5404.html</wfw:commentRss><trackback:ping>http://www.cppblog.com/wy/services/trackbacks/5404.html</trackback:ping><description><![CDATA[#include &lt;string&gt;<br />#include &lt;vector&gt;<br />#include &lt;iostream&gt;<br /><br />#include &lt;windows.h&gt;<br />#include &lt;conio.h&gt;<br /><br /><br /><br /><font color="#0000ff">int</font> SearchDirectory(std::vector&lt;std::string&gt; &amp;refvecFiles,<br />                    <font color="#0000ff">const</font> std::string        &amp;refcstrRootDirectory,<br />                    <font color="#0000ff">const</font> std::string        &amp;refcstrExtension,<br />                    <font color="#0000ff">bool</font>                     bSearchSubdirectories = <font color="#0000ff">true</font>)<br />{<br />  std::string     strFilePath;             <font color="#008800">// Filepath</font><br />  std::string     strPattern;              <font color="#008800">// Pattern</font><br />  std::string     strExtension;            <font color="#008800">// Extension</font><br />  HANDLE          hFile;                   <font color="#008800">// Handle to file</font><br />  WIN32_FIND_DATA FileInformation;         <font color="#008800">// File information</font><br /><br /><br />  strPattern = refcstrRootDirectory + <font color="#880000">"\\*.*"</font>;<br /><br />  hFile = ::FindFirstFile(strPattern.c_str(), &amp;FileInformation);<br />  <font color="#0000ff">if</font>(hFile != INVALID_HANDLE_VALUE)<br />  {<br />    <font color="#0000ff">do</font><br />    {<br />      <font color="#0000ff">if</font>(FileInformation.cFileName[0] != <font color="#880000">'.'</font>)<br />      {<br />        strFilePath.erase();<br />        strFilePath = refcstrRootDirectory + <font color="#880000">"\\"</font> + FileInformation.cFileName;<br /><br />        <font color="#0000ff">if</font>(FileInformation.dwFileAttributes &amp; FILE_ATTRIBUTE_DIRECTORY)<br />        {<br />          <font color="#0000ff">if</font>(bSearchSubdirectories)<br />          {<br />            <font color="#008800">// Search subdirectory</font><br />            <font color="#0000ff">int</font> iRC = SearchDirectory(refvecFiles,<br />                                      strFilePath,<br />                                      refcstrExtension,<br />                                      bSearchSubdirectories);<br />            <font color="#0000ff">if</font>(iRC)<br />              <font color="#0000ff">return</font> iRC;<br />          }<br />        }<br />        <font color="#0000ff">else</font><br />        {<br />          <font color="#008800">// Check extension</font><br />          strExtension = FileInformation.cFileName;<br />          strExtension = strExtension.substr(strExtension.rfind(<font color="#880000">"."</font>) + 1);<br /><br />          <font color="#0000ff">if</font>(strExtension == refcstrExtension)<br />          {<br />            <font color="#008800">// Save filename</font><br />            refvecFiles.push_back(strFilePath);<br />          }<br />        }<br />      }<br />    } <font color="#0000ff">while</font>(::FindNextFile(hFile, &amp;FileInformation) == TRUE);<br /><br />    <font color="#008800">// Close handle</font><br />    ::FindClose(hFile);<br /><br />    DWORD dwError = ::GetLastError();<br />    <font color="#0000ff">if</font>(dwError != ERROR_NO_MORE_FILES)<br />      <font color="#0000ff">return</font> dwError;<br />  }<br /><br />  <font color="#0000ff">return</font> 0;<br />}<br /><br /><br /><font color="#0000ff">int</font><font color="#0000ff">main</font>()<br />{<br />  <font color="#0000ff">int</font>                      iRC         = 0;<br />  std::vector&lt;std::string&gt; vecAviFiles;<br />  std::vector&lt;std::string&gt; vecTxtFiles;<br /><br /><br />  <font color="#008800">// Search 'c:' for '.avi' files including subdirectories</font><br />  iRC = SearchDirectory(vecAviFiles, <font color="#880000">"c:"</font>, <font color="#880000">"avi"</font>);<br />  <font color="#0000ff">if</font>(iRC)<br />  {<br />    std::cout &lt;&lt; <font color="#880000">"Error "</font> &lt;&lt; iRC &lt;&lt; std::endl;<br />    <font color="#0000ff">return</font> -1;<br />  }<br /><br />  <font color="#008800">// Print results</font><br />  <font color="#0000ff">for</font>(std::vector&lt;std::string&gt;::iterator iterAvi = vecAviFiles.begin();<br />      iterAvi != vecAviFiles.end();<br />      ++iterAvi)<br />    std::cout &lt;&lt; *iterAvi &lt;&lt; std::endl;<br /><br />  <font color="#008800">// Search 'c:\textfiles' for '.txt' files excluding subdirectories</font><br />  iRC = SearchDirectory(vecTxtFiles, <font color="#880000">"c:\\textfiles"</font>, <font color="#880000">"txt"</font>, <font color="#0000ff">false</font>);<br />  <font color="#0000ff">if</font>(iRC)<br />  {<br />    std::cout &lt;&lt; <font color="#880000">"Error "</font> &lt;&lt; iRC &lt;&lt; std::endl;<br />    <font color="#0000ff">return</font> -1;<br />  }<br /><br />  <font color="#008800">// Print results</font><br />  <font color="#0000ff">for</font>(std::vector&lt;std::string&gt;::iterator iterTxt = vecTxtFiles.begin();<br />      iterTxt != vecTxtFiles.end();<br />      ++iterTxt)<br />    std::cout &lt;&lt; *iterTxt &lt;&lt; std::endl;<br /><br />  <font color="#008800">// Wait for keystroke</font><br />  _getch();<br /><br />  <font color="#0000ff">return</font> 0;<br />}<br /><img src ="http://www.cppblog.com/wy/aggbug/5404.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cppblog.com/wy/" target="_blank">鱼儿</a> 2006-04-12 16:57 <a href="http://www.cppblog.com/wy/articles/5404.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>