2012年8月25日 星期六

[C++] Sample for Using stdlib to implement Extend Quick Sort function

As last example, I use standard library to implement quick sort again.

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <algorithm>

void quickSortEx(int[], int, bool, int, int);
int cmp(const void* a, const void* b);

int _tmain(int argc, _TCHAR* argv[])
{
    srand(time(NULL));
    const int count = 10;
    int number[count] = {0};

    printf("Before: ");
    int i;
    for(i = 0; i < count; i++) {
        number[i] = rand() % 100;
        printf("%d ", number[i]);
    }
    printf("\n");

    quickSortEx(number, count, true, 0, count-1);

    printf("Afer: ");
    for(i = 0; i < count; i++)
        printf("%d ", number[i]);

    printf("\n");
    return 0;
}

void quickSortEx(int number[], int count, bool desc, int left, int right)
{
    qsort(number, count, sizeof(number[0]), cmp);

    if (desc)
        std::reverse(number, number+count);
}

int cmp(const void* a, const void* b)
{
    const int x = *static_cast<const int*>(a);
    const int y = *static_cast<const int*>(b);

    if (x == y)
        return 0;

    return x > y ? 1 : -1;
}


Reference:
http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/
http://www.cplusplus.com/reference/algorithm/reverse/

2012年8月24日 星期五

[C++] A sample for Extended Quick Sort

I need to implement a function to sort items with specified ascending order.
I modify other's sample as below.

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void quickSortEx(int[], int, bool, int, int);
void swap(int &x, int &y);

int _tmain(int argc, _TCHAR* argv[])
{
    srand(time(NULL));
    const int count = 10;
    int number[count] = {0};
 
    printf("Before: ");
    int i;
    for(i = 0; i < count; i++) {
        number[i] = rand() % 100;
        printf("%d ", number[i]);
    }
    printf("\n");

    quickSortEx(number, count, false, 0, count-1);

    printf("Afer: ");
    for(i = 0; i < count; i++)
        printf("%d ", number[i]);
 
    printf("\n");
    return 0;
}

void quickSortEx(int number[], int count, bool desc, int left, int right) {
    if(left < right) {
        int i = left;
        int j = right + 1;

        while(1) {
            // To find the item should sort after 'left'
            while(i + 1 < count && (desc ? number[left] < number[++i] : number[++i] < number[left]));
            // To find the item should sort before 'left'
            while(j -1 > -1 && (desc ? number[left] > number[--j] : number[--j] > number[left])) ;
            if(i >= j)
                break;
            swap(number[i], number[j]);
        }

        swap(number[left], number[j]);

        quickSortEx(number, count, desc, left, j-1);
        quickSortEx(number, count, desc, j+1, right);
    }
}

void swap(int &x, int &y)
{
    int temp;
    temp = x;
    x = y;
    y = temp;
}

Reference:
http://caterpillar.onlyfun.net/Gossip/AlgorithmGossip/QuickSort1.htm
http://emn178.pixnet.net/blog/post/88613503-%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F%E6%B3%95(quick-sort)

2012年8月23日 星期四

[C++] Sample for String Compare

It is a simple sample for understanding how to implement a function to compare two string.

#include "stdafx.h"
#include <string.h>
#include <iostream>

using namespace std;

int codePointCompare(const char* c1, const char* c2)
{
 int l1 = strlen(c1);
 int l2 = strlen(c2);
        const unsigned lmin = l1 < l2 ? l1 : l2;
        unsigned pos = 0;
        while (pos < lmin && *c1 == *c2)
 {
             c1++;
             c2++;
             pos++;
        }

        if (pos < lmin)
             return (c1[0] > c2[0]) ? 1 : -1;

        if (l1 == l2)
             return 0;

 return (l1 > l2) ? 1 : -1;
}

int _tmain(int argc, _TCHAR* argv[])
{
 char* c1 = new char[1024];
 char* c2 = new char[1024];
 cout << "please input first string:";
 cin >> c1;
 cout << "please input second string:";
 cin >> c2;

 cout << codePointCompare(c1, c2);
 return 0;
}


Reference:
http://trac.webkit.org/changeset/110822/trunk/Source/JavaScriptCore/wtf/text/StringImpl.cpp

2012年8月20日 星期一

[C++] Threading Sample

This is a simple sample for understanding of thread create in C++.

#include "stdafx.h"
#include <windows.h>
#include <process.h>
#include <stdio.h>

void myfunc(int n);

int _tmain(int argc, _TCHAR* argv[])
{
    HANDLE thd[2];
    DWORD tid;

    printf("Thead Start.\n");

    for (int i=0; i<2; i++)
    {
        thd[i] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)myfunc, (void*)i, 0, &tid);
        printf("Thread %d is start \n",tid);
    }


    Sleep(1000);

    printf("main is end \n");

    system("pause");
}

void myfunc(int n)
{
    int i;
    for(int i=0;i<5;i++){
        printf("Thread %d, index=%d\n", n, i);
        Sleep(1000);
    }
    printf("Thread %d is over \n", getpid());
}

Reference:
http://wuminfajoy.blogspot.tw/2010/10/c.html

2012年8月16日 星期四

[C++] Create GUID

You can create GUID by using CoCreateGuid API.
I copy example source code from my reference article for memo as below.


#include "stdafx.h"
#include <objbase.h>
#include <string>

using namespace std;

wstring GetGUID()
{
    _TUCHAR *guidStr = NULL;

    GUID *pguid = new GUID;

    CoCreateGuid(pguid);

    // Convert the GUID to a string
    UuidToString(pguid, (RPC_WSTR*)&guidStr);
    delete pguid;
    return wstring(guidStr);
}

int _tmain(int argc, _TCHAR* argv[])
{
wstring guid = GetGUID();
    wprintf(guid.c_str());
    return 0;
}



Reference:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms688568(v=vs.85).aspx
http://www.dotblogs.com.tw/alonstar/archive/2011/09/05/mfc_32bit_64bit.aspx

2012年8月12日 星期日

[MS SQL] Performance counter registry hive consistency check

To avoid meet the problem again, I memo the solution here.

While installing SQLServer 2008 on Windows 7 64bit - Traditional Chinese Version.
I got an error message told me "Performance counter registry hive consistency check".
It would not happen on English version OS.
Here is an article will help.
http://www.dotblogs.com.tw/lastsecret/archive/2010/06/14/15865.aspx

In addition, you should execute window update to download Visual Studio 2008 sp1 if you like to install SQL Server 2008 Management Studio. Otherwise you'll got error message as "Another version of Microsoft Visual Studio 2008 has been detected on this system that must be updated to SP1.  Please update all Visual Studio 2008 installations to SP1 level, by visiting Microsoft Update."



2012年7月19日 星期四

Certificate Store Operations

Example to get certificate from system.


#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include <Wincrypt.h>
#define MY_ENCODING_TYPE  (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
void MyHandleError(char *s);

int _tmain(int argc, _TCHAR* argv[])
{
    //--------------------------------------------------------------------
    // Copyright (C) Microsoft.  All rights reserved.
    // Declare and initialize variables.

    HCERTSTORE  hSystemStore;              // System store handle
    PCCERT_CONTEXT  pDesiredCert = NULL;   // Set to NULL for the first call to CertFindCertificateInStore
    PCCERT_CONTEXT  pCertContext;


    //-------------------------------------------------------------------
    // Open the My system store using CertOpenStore.

    if(hSystemStore = CertOpenStore(
         CERT_STORE_PROV_SYSTEM,            // System store will be a virtual store
         0,                                 // Encoding type not needed with this PROV
         NULL,                              // Accept the default HCRYPTPROV
         CERT_SYSTEM_STORE_CURRENT_USER,    // Set the system store location in the registry
         L"MY"))                            // Could have used other predefined  system stores including Trust, CA, or Root
    {
       printf("Opened the MY system store. \n");
    }
    else
    {
       MyHandleError( "Could not open the MY system store.");
    }



    //-------------------------------------------------------------------
    // Find the certificates in the system store. 
    while(pCertContextEnum=CertEnumCertificatesInStore(
          hSystemStore,
          pCertContextEnum)) // on the first call to the function, this parameter is NULL  on all subsequent                calls,  this parameter is the last pointer returned by the function
    {
        if(CertGetNameString(
           pCertContextEnum,
           CERT_NAME_SIMPLE_DISPLAY_TYPE,
           0,
           NULL,
           pszNameString,
           128))
        {
            printf("\nCertificate for %s \n",pszNameString);
        }
        else
           fprintf(stderr,"CertGetName failed. \n");
    } // End of while.



    //-------------------------------------------------------------------
    // Get a certificate that has the string "ninna.tw@gmail.com" in its subject. 

    if(pDesiredCert=CertFindCertificateInStore(
          hSystemStore,
          MY_ENCODING_TYPE,             // Use X509_ASN_ENCODING
          0,                            // No dwFlags needed 
          CERT_FIND_SUBJECT_STR,        // Find a certificate with a subject that matches the string in the next parameter
          L"ninna.tw@gmail.com",     // The Unicode string to be found in a certificate's subject
          NULL))                        // NULL for the first call to the function In all subsequent calls, it is the last pointer returned by the function
    {
      printf("The desired certificate was found. \n");
    }
    else
    {
       MyHandleError("Could not find the desired certificate.");
    }
    //-------------------------------------------------------------------
    // pDesiredCert is a pointer to a certificate with a subject that 
    // includes the string "ninna.tw@ gmail.com ", the string is 
    // passed as parameter #5 to the function.


    //-------------------------------------------------------------------
    // Close the stores.

    if(hSystemStore)
        CertCloseStore(
            hSystemStore,
            CERT_CLOSE_STORE_CHECK_FLAG);

    printf("All of the stores are closed. \n");

return 0;
}

//-------------------------------------------------------------------
// This example uses the function MyHandleError, a simple error
// handling function, to print an error message and exit 
// the program. 
// For most applications, replace this function with one 
// that does more extensive error reporting.

void MyHandleError(char *s)
{
    fprintf(stderr,"An error occurred in running the program. \n");
    fprintf(stderr,"%s\n",s);
    fprintf(stderr, "Error number %x.\n", GetLastError());
    fprintf(stderr, "Program terminating. \n");
    exit(1);
} // end MyHandleError




You should add dependency for using static functions.
Right click on project -> Property -> Linker -> Input ->Additional Dependencies -> add crypt32.lib



Reference:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa382037(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/aa382363(v=vs.85).aspx

2012年5月25日 星期五

Watch Virtual / Physical Memory Usage

With previous article http://twnin.blogspot.com/2012/05/watch-process-memory-usage.html
There is another way to watch memory usage in program with win32 api.


    MEMORYSTATUS ms;
    ms.dwLength = sizeof(ms);
    GlobalMemoryStatus(&ms);

    const int nBufSize = 512;
    TCHAR chBuf[nBufSize];
    ::ZeroMemory(chBuf,nBufSize);

    // Process-specific info (for calling process)
    wsprintf(chBuf,_T("TotalVirtual: %ld\n"), ms.dwTotalVirtual);
    OutputDebugString(chBuf);
    wsprintf(chBuf,_T("AvailVirtual: %ld\n"), ms.dwAvailVirtual);
    OutputDebugString(chBuf);

    // Process virtual memory usage (reserved + commit)
    wsprintf(chBuf,_T("UsageVirtual: %ld\n"), ms.dwTotalVirtual - ms.dwAvailVirtual);
    OutputDebugString(chBuf);

    // System info
    wsprintf(chBuf,_T("MemoryLoad: %ld\n"), ms.dwMemoryLoad);
    OutputDebugString(chBuf);
    wsprintf(chBuf,_T("TotalPhys: %ld\n"), ms.dwTotalPhys);
    OutputDebugString(chBuf);
    wsprintf(chBuf,_T("AvailPhys: %ld\n"), ms.dwAvailPhys);
    OutputDebugString(chBuf);

    // System usage
    wsprintf(chBuf,_T("UsagePhys: %ld\n"), ms.dwTotalPhys - ms.dwAvailPhys);
    OutputDebugString(chBuf);

    // Unused/unsupported
    wsprintf(chBuf,_T("TotalPageFile: %lu\n"), ms.dwTotalPageFile);
    OutputDebugString(chBuf);
    wsprintf(chBuf,_T("AvailPageFile: %lu\n"), ms.dwAvailPageFile);
    OutputDebugString(chBuf);

Watch Process Memory Usage


To watch current process memory usage, we can use GetProcessMemoryInfo to get paging information.
It is sample code below.

    HANDLE hProcess = ::GetCurrentProcess();
    PROCESS_MEMORY_COUNTERS pmc;
    pmc.cb = sizeof(PROCESS_MEMORY_COUNTERS);
    ::GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc));

    const int nBufSize = 512;
    TCHAR chBuf[nBufSize];
    ::ZeroMemory(chBuf,nBufSize);

    wsprintf(chBuf,_T("PageFaultCount: 0x%08X\n"), pmc.PageFaultCount );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("PeakWorkingSetSize: 0x%08X\n"),
    pmc.PeakWorkingSetSize );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("WorkingSetSize: 0x%08X\n"), pmc.WorkingSetSize );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("QuotaPeakPagedPoolUsage: 0x%08X\n"),
    pmc.QuotaPeakPagedPoolUsage );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("QuotaPagedPoolUsage: 0x%08X\n"),
    pmc.QuotaPagedPoolUsage );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("QuotaPeakNonPagedPoolUsage: 0x%08X\n"),
    pmc.QuotaPeakNonPagedPoolUsage );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("QuotaNonPagedPoolUsage: 0x%08X\n"),
    pmc.QuotaNonPagedPoolUsage );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("PagefileUsage: 0x%08X\n"), pmc.PagefileUsage );
    OutputDebugString(chBuf);

    wsprintf(chBuf,_T("PeakPagefileUsage: 0x%08X\n"),
    pmc.PeakPagefileUsage );
    OutputDebugString(chBuf);

    CloseHandle(hProcess);


Reference:
http://msdn.microsoft.com/en-us/library/ms682050(v=VS.85).aspx
http://blog.csdn.net/caimouse/article/details/1947575

Work around link error:
error lnk2019: unresolved external symbol _getprocessmemoryinfo@12 referenced in function
http://lanvu.wordpress.com/tag/error-lnk2019-unresolved-external-symbol-_getprocessmemoryinfo12-referenced-in-function/

It seems doesn't work on windows ce.
https://groups.google.com/group/microsoft.public.pocketpc.developer/browse_thread/thread/22c685d1df9ec17d/e05ad892433d56aa?lnk=raot&pli=1

Structure of PROCESS_MEMORY_COUNTERS
http://blog.csdn.net/zhsp1029/article/details/3162048

2012年5月17日 星期四

[C++] error C2662 cannot convert 'this' pointer from 'const class' to 'class &


Look at following sample
class myClass
{
public:
    int get();
private:
    int m_member;
};

int myClass::get()
{
    return m_member;
}

int main()
{
    const myClass own;
    own.get();  // compiling error
    return 0;
}

A const object try to call non-const function, it is risk to change value of const object.
For the reason, we have to define myClass::get() to be a const function so that we could call the function by a const object.
int myClass::get() const

Or we also can define own to be a non-const object.
myClass own;


Reference: 
http://hi.baidu.com/idealsoft/blog/item/629ae129a7f14afb99250af4.html http://forums.codeguru.com/archive/index.php/t-416873.html