2014-03-03 26 views
0

我試圖使用Windows示例之一來獲取一些CPU數據。當我嘗試調試下面的代碼時,我收到消息「命令行必須包含有效的日誌文件名」我正在使用MS Visual studio 2013,並且對Total Processor time%感興趣。將性能數據寫入日誌文件

請指教。

更多關於代碼的細節: http://msdn.microsoft.com/en-us/library/windows/desktop/aa373228(v=vs.85).aspx

驗證碼:

#include <windows.h> 
#include <stdio.h> 
#include <pdh.h> 
#include <pdhmsg.h> 

#pragma comment(lib, "pdh.lib") 

CONST PWSTR COUNTER_PATH = L"\\Processor(0)\\% Processor Time"; 
CONST ULONG SAMPLE_INTERVAL_MS = 1000; 

void DisplayCommandLineHelp(void) 
{ 
    wprintf(L"The command line must include a valid log file name.\n"); 
} 

void wmain(int argc, WCHAR **argv) 
{ 
    HQUERY hQuery = NULL; 
    HLOG hLog = NULL; 
    PDH_STATUS pdhStatus; 
    DWORD dwLogType = PDH_LOG_TYPE_CSV; 
    HCOUNTER hCounter; 
    DWORD dwCount; 

    if (argc != 2) 
    { 
     DisplayCommandLineHelp(); 
     goto cleanup; 
    } 

    // Open a query object. 
    pdhStatus = PdhOpenQuery(NULL, 0, &hQuery); 

    if (pdhStatus != ERROR_SUCCESS) 
    { 
     wprintf(L"PdhOpenQuery failed with 0x%x\n", pdhStatus); 
     goto cleanup; 
    } 

    // Add one counter that will provide the data. 
    pdhStatus = PdhAddCounter(hQuery, 
     COUNTER_PATH, 
     0, 
     &hCounter); 

    if (pdhStatus != ERROR_SUCCESS) 
    { 
     wprintf(L"PdhAddCounter failed with 0x%x\n", pdhStatus); 
     goto cleanup; 
    } 

    // Open the log file for write access. 
    pdhStatus = PdhOpenLog(argv[1], 
     PDH_LOG_WRITE_ACCESS | PDH_LOG_CREATE_ALWAYS, 
     &dwLogType, 
     hQuery, 
     0, 
     NULL, 
     &hLog); 

    if (pdhStatus != ERROR_SUCCESS) 
    { 
     wprintf(L"PdhOpenLog failed with 0x%x\n", pdhStatus); 
     goto cleanup; 
    } 

    // Write 10 records to the log file. 
    for (dwCount = 0; dwCount < 10; dwCount++) 
    { 
     wprintf(L"Writing record %d\n", dwCount); 

     pdhStatus = PdhUpdateLog(hLog, NULL); 
     if (ERROR_SUCCESS != pdhStatus) 
     { 
      wprintf(L"PdhUpdateLog failed with 0x%x\n", pdhStatus); 
      goto cleanup; 
     } 

     // Wait one second between samples for a counter update. 
     Sleep(SAMPLE_INTERVAL_MS); 
    } 

cleanup: 

    // Close the log file. 
    if (hLog) 
     PdhCloseLog(hLog, 0); 

    // Close the query object. 
    if (hQuery) 
     PdhCloseQuery(hQuery); 
} 

回答

0
if (argc != 2) 
{ 
    DisplayCommandLineHelp(); 
    goto cleanup; 
} 

這是在這裏你的答案。您需要設置項目以在程序運行時向程序傳遞文件名。

argc計算您的程序收到的命令行參數數量。它總是得到至少一個,程序本身的名稱。但是這個程序需要第二個,要寫入的日誌文件的名稱。

+0

好的,我應該在哪裏添加文件名和什麼是擴展名? – Yasz

+0

你可以使用任何你喜歡的擴展名。和[這個答案](http://stackoverflow.com/a/298713/2245528)顯示你在哪裏添加命令行參數到你的項目。把文件名放在那裏。 – computerfreaker

+0

謝謝,它工作:) – Yasz