2015年3月29日 星期日

Understanding Wave Format, and Implement a Wave Reader



I found there is no detail discussion for extra data of wave format. Here I post a explicit (for myself) wave header in below:

Data in each column are all in little endian.


Sample Value size in byte Description offset
Chunk ID 4 Marks the file as a riff file.,Characters are each 1 byte long
That should be "RIFF".
0
Chunk Size 4 4 + (8 + SubChunk1Size) + (8 + SubChunk2Size) 4
Format 4 File Type Header.,For wave purposes, it always equals "WAVE". 8
Format Mark 4 Format chunk marker.,Includes trailing null. should be "fmt " 12
Sub-chunk 1 Size 4 Length of format data 16
Audio Format 2 PCM = 1 (i.e. Linear quantization),Values other than 1 indicate some,form of compression. 20
Number of Channels 2 Mono = 1, Stereo = 2, etc. 22
Sampling Rate 4 Number of Samples per second 24
Byte Rate 4 Byte per second, it should be SamplingRate*NumberOfChannel*BitsPerSample/8 28
Block Align 2 Byte for whole sampling point,, it should be NumberOfChannel*BitsPerSample/8 32
Bits Per Sample 2 8 bits = 8, 16 bits = 16 34
Extra Data Header ?(2) Extra wave note, in most,case, that "size" is 0 (no extra data), or 2.
This size could be computed by "Subchunk1Size - 16 "
36
Extra Data ? extra data, most for audio notes(artist, album, publish year, music type. etc) ?
Sub chunk 2 ID 4 Contains the letters "data" ??
Sub chunk 2 size 4 Audio data length ?? + 4
Audio data Audio data length Audio data ?? + 8


Lots posts has discuss wave file without extra data, in here, I just note about extra data:

    Length of extra data  is various, but it should be multiple of 4.

    Extra data is useful for audience, it is not junk. If your wave file is within extra data, just print that data in your console or window.

    To find where is the end of extra data, is to find where is the beginning of sub-chunk2. That is, to find the "data" string.


Below is my implement to read a wave file in C.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifndef TRUE
#define TRUE        (1)
#define FALSE        (0)
#endif

#define MAX_STR_LEN       (256)


#ifdef _MSC_VER
#pragma warning(disable:4996) /*fuss*/

#include <stdarg.h>

int snprintf(char *pBuf, size_t maxN, const char *pFmt, ...)
{
 int len; 
 va_list argList; 
 
 va_start(argList, pFmt); 

 len = vsprintf_s(pBuf, maxN, pFmt, argList);

 va_end(argList); 

 return len;
}/*snprintf*/

#endif


unsigned int GetFileSize(FILE *pFile)
{
 unsigned int currentLen, fileSize;

 currentLen = ftell(pFile);

 fseek(pFile,0, SEEK_END);
 fileSize = ftell(pFile);   

 fseek(pFile,currentLen ,SEEK_SET);
 

 return (unsigned int)fileSize;

}/*GetFileSize*/


unsigned int GetRemainderFileSize(FILE *pFile)
{
 unsigned int currentLen, fileSize;

 currentLen = ftell(pFile);

 fseek(pFile,0, SEEK_END);
 fileSize = ftell(pFile);   

 fseek(pFile,currentLen ,SEEK_SET);

 return (unsigned int)(fileSize - currentLen );

}/*GetRemainderFileSize*/


typedef struct _WaveFeature
{
 char               ChunkID[4];
 /* "RIFF" Header      */ 
 
 unsigned int       ChunkSize;
 /* 36 + SubChunk2Size, or more precisely:4 + (8 + SubChunk1Size) + (8 + SubChunk2Size)  */
 
 char               Format[4];
 /* "WAVE"  */
 
 char               fmt[4];
 /* "fmt "*/
 
 unsigned int       Subchunk1Size;
 /* Size of the fmt chunk */
 
 unsigned short     AudioFormat;
 /* Audio format 1=PCM,6=mulaw,7=alaw, 257=IBM Mu-Law, 258=IBM A-Law, 259=ADPCM */
 
 unsigned short     NumChannels;
 /* Number of channels 1=Mono 2=Sterio */
 
 unsigned int       SampleRate;
 /* Sampling Frequency in Hz*/
 
 unsigned int       ByteRate;
 /* bytes per second,  SampleRate * NumChannels * BitsPerSample/8*/
 
 unsigned short     BlockAlign;
 /* 2=16-bit mono, 4=16-bit stereo, NumChannels * BitsPerSample/8*/
 
 unsigned short     BitsPerSample;
 /* Number of bits per sample  */
} WaveFeature;


typedef struct _WaveData
{
 char               Subchunk2ID[4]; /* "data"  string   */
 unsigned int       Subchunk2Size; /* Sampled data length    */
} WaveData;


int GetWaveFeatures(unsigned char *pWaveHead, unsigned short *pNumChannel, 
    unsigned int *pNumSamplesPerSec,  unsigned short *pBitsPerSample, 
    unsigned int *pBytesPerSec)
{
 
 char charWord[MAX_STR_LEN];  
 snprintf(&charWord[0], MAX_STR_LEN, "RIFF");
 if(0 != memcmp( &pWaveHead[0], &charWord[0], 4) ) 
  return -1;   
 
 
 snprintf(&charWord[0], MAX_STR_LEN, "WAVE");
 if(0 != memcmp( &pWaveHead[8], &charWord[0], 4) ) 
  return -1;   
 
 snprintf(&charWord[0], MAX_STR_LEN, "fmt ");
 if(0 != memcmp( &pWaveHead[12], &charWord[0], 4) ) 
  return -1; 

 unsigned int  chunkSize;
 memcpy( &chunkSize, &pWaveHead[16], 4);

 *pNumChannel = *((unsigned short*)(pWaveHead + 22));
 *pNumSamplesPerSec = *((unsigned int*)(pWaveHead + 24));
 *pBitsPerSample = *((unsigned short*)(pWaveHead + 34));
 
 *pBytesPerSec = *((unsigned int*)(pWaveHead + 28)); /*ByteRate         */
 if(*pBytesPerSec != (*pNumSamplesPerSec)*(*pNumChannel)*(*pBitsPerSample/8))
  return -2;

 int blockAlign;

 blockAlign = *((unsigned short*)(pWaveHead + 32)); 
 if(blockAlign != (*pNumChannel)*(*pBitsPerSample/8))
  return -2;

 return 0;
}/*GetWaveInfo*/


int GetWaveLength(unsigned char *pWaveHead, unsigned int *pAudioDataLen)
{
 char charWord[MAX_STR_LEN];  
 snprintf(&charWord[0], MAX_STR_LEN, "data");

 
 if(0 != memcmp( &pWaveHead[0], &charWord[0], 4) )
  return -1;  
 
 *pAudioDataLen = *((unsigned int*)(pWaveHead + 4));

 return 0;
}/*GetWaveLength*/


int main(int argc, char *argv[])
{
 
 char inputFileName[MAX_STR_LEN];

 snprintf(&inputFileName[0], MAX_STR_LEN, "03 Rondeau in C Minor.wav");
    
#if defined(__MACH__) && defined(_DEBUG)/*xcode stupid...*/
    char tempStr[MAX_STR_LEN];
    snprintf(&tempStr[0], MAX_STR_LEN, "../../../../../");
    strncat(&tempStr[0], &inputFileName[0], strnlen(&inputFileName[0],MAX_STR_LEN));
    memset(&inputFileName[0], 0, MAX_STR_LEN);
    strncpy(&inputFileName[0], &tempStr[0], strnlen(&tempStr[0],MAX_STR_LEN));
#endif
    
 int k; 
 k = 0;

 while (k < argc) 
 {
  if( 0 == strncmp("-i",argv[k], MAX_STR_LEN))
  {
   if(k + 1 < argc)
   {
    snprintf(inputFileName, MAX_STR_LEN, "%s", argv[k + 1]); 
   }
   else
   {
    printf("-i should be fellowed by input wav file.");
   }/*if*/
  }/*if strncmp*/  

  k++;
 }/*while opt*/

 FILE *pWaveFile;

 pWaveFile = fopen(&inputFileName[0], "rb");

 if(NULL == pWaveFile)
 {
  printf("open file %s error \n", inputFileName);
  return -1;
 }/*if NULL == pWaveFile*/

 printf("file : %s\n", inputFileName);
 
 WaveFeature wavFea;

 fread(&wavFea, sizeof(WaveFeature), 1, pWaveFile);

 unsigned short nChannel; 
 unsigned int nSamplesPerSec;
 unsigned short bitsPerSample;
 unsigned int audioDataLen;
 unsigned int bytesPerSec;
 int isContentExtaBytes;

 int sts;
 sts = GetWaveFeatures((unsigned char*)&wavFea, &nChannel, &nSamplesPerSec, 
  &bitsPerSample,&bytesPerSec);

 
 if(-1 == sts)
 {
  printf("not a wav format\n");
  return -1;
 }
 else if(-2 == sts)
 {
  printf("wav format do not be consisted\n");
  return -1;
 }
 else if(-3 == sts)
 {
  printf("extra parameters are not known\n");
 }/*if -1 == sts*/

 printf("%u channel\n", nChannel);
 printf("simpling frequency = %u\n", nSamplesPerSec);
 printf("%u bits Per Sample\n", bitsPerSample);
 

 {/*scan the data flag, and print extra infomation...*/
  char readBuff[MAX_STR_LEN];
  char charWorddata[8];
  unsigned int ii, jj;
 
  memset(&readBuff[0], 0, MAX_STR_LEN);
  memset(&charWorddata[0], 0, 8);
  snprintf(&charWorddata[0], 8, "data");
 
  unsigned int remainLen;
  int isFoundDataFlag;
  isFoundDataFlag = FALSE;
  remainLen = GetRemainderFileSize(pWaveFile);

  ii = 0;
  while(MAX_STR_LEN < remainLen)
  {

   fread(&readBuff[0], 1, MAX_STR_LEN, pWaveFile);
   jj = 0;
   while(jj < MAX_STR_LEN)
   {
    if(0 == memcmp(&readBuff[jj], &charWorddata[0], 4))
    {
     isFoundDataFlag = TRUE; 
     break;
    }
    else
    {
     if(0 != jj && 0 == readBuff[jj] &&  0 != readBuff[jj - 1])
      printf("\n");
     else
      printf("%c", readBuff[jj]);
    }/*if */

    jj++; 
   }
   if(FALSE != isFoundDataFlag)
    break;
   remainLen -= MAX_STR_LEN;
   ii++;
  }

  if(FALSE == isFoundDataFlag)
  {
   printf("no data flag has been found\n");
   return -2;
  }/*if FALSE == isFoundDataFlag*/

  fseek(pWaveFile, -(MAX_STR_LEN-jj), SEEK_CUR);
 }/*local variables*/


 WaveData wavData;

 fread(&wavData, sizeof(WaveData), 1, pWaveFile);
 sts = GetWaveLength((unsigned char*)&wavData, &audioDataLen);

 if(-1 == sts)
 {
  printf("not a wav format\n");
  return -1;
 }

 audioDataLen = wavData.Subchunk2Size; 

 if(GetRemainderFileSize(pWaveFile) != audioDataLen)
 {
  printf("warning: data length is not consistency\n");
  
  unsigned int remainderLen;
  remainderLen = GetRemainderFileSize(pWaveFile);

  printf("remainderLen = %u\n", remainderLen);  
  printf("audioDataLen = %u\n", audioDataLen);

  if((unsigned int)audioDataLen > remainderLen)
   audioDataLen = remainderLen;
 }/*if */

 float audioPlayTime;
 audioPlayTime = (float)audioDataLen/bytesPerSec;

 printf("audio time = %3.2f sec", audioPlayTime);

 if(audioPlayTime > 60.0f)
  printf(" (%4.3fmins)\n", audioPlayTime/60.0f); 
 else
  printf("\n");

 return 0;
 
}/*main*/


You could use command line -i XXX.wav to specified what file you want to read.



Above is the result when I read a wave file, 03 Rondeau in C Minor.wav.






2015年3月28日 星期六

Connect to a Specified Wifi Router in Macintosh, by Objective C


     Similar to the other article of mine: In here, I post the code which could connect to target wifi router. The Xcode project be set as : Base SDK is 10.7, and  OSX deployment SDK as 10.5. The code depends on the frame work CoreWLAN.framework of 10.7 (it exists in /Developer/SDKs/MacOSX10.7.sdk/System/Library/Frameworks by default , if you have installed 10.7 SDK), you should add it to your Xcode project. The could running in OS X 10.8 and 10.9  without any wrong(both 32 and 64 bit).

    If you do not install 10.7 SDK, to set the environment, it is necessary to download  OS X 10.7 SDK. you could download it from here ( need apple id). Refer to the article in stack overflow, SDKs of OS X are bundled with  each version of Xcode (10.5 -> 3.1, 10.6 ->3.2, 10.7 ->4.3, 10.8 -> 5.1, 10.9 -> 6.0, respectively). In here, you should download Xcode 4.3, extract the 10.7 SDK to your computer.



The code is in objective-C, but the function call is C-style, for C/C++ calling compatible.


#import <CoreWLAN/CoreWLAN.h>


int ConnectToTargetWifiSSID(char *pSSIDName, char *pPassword)
{
    @autoreleasepool {
        if(NULL == pSSIDName)
            return -1;
        
        NSString *ssidName = [ [NSString alloc] initWithUTF8String : pSSIDName ];
        //NSLog(@"%@", ssidName);
        
        
        CWInterface *currentInterface = [CWInterface interface];
        
        if( [ssidName isEqualToString: [currentInterface ssid]])
        {
            printf("current is %s\n", pSSIDName);
            return 1;
        }/*if*/
        
        if( NO== currentInterface.powerOn)
        {
            printf("wireless card has been turn off\n");
            return -1;
        }/*if */
        
        NSArray *networks = [[currentInterface scanForNetworksWithName:nil error:nil] allObjects];
        
        if(0 == [networks count])
        {
            printf("no available wifi ap\n");
            return -2;
        }/*if */
        
        printf("available wifi ssid name:\n");
        for(int i = 0; i< [networks count]; i++){
            printf("%s \n", [[[networks objectAtIndex:i] ssid] cStringUsingEncoding:NSUTF8StringEncoding]);
        }/*for*/
        
       
        int iii;
        iii = -1;
     
        
        for(int i = 0; i< [networks count]; i++){
            if([ ssidName isEqualToString: [[networks objectAtIndex:i] ssid] ])
            {
                iii = i;
                break;
            }/*if*/
        }/*for*/

        if(-1 == iii)
        {
            printf("no available wifi ssid name marches %s\n", pSSIDName);
            return -3;
        }/*if*/
        
        NSString *password;
        
        if(NULL == pPassword)
            password = [ [NSString alloc] initWithFormat:@"%@",@"    "];
        else
            password = [ [NSString alloc] initWithUTF8String : pPassword];
        
        //NSLog(@"%@", password);
        
        CWNetwork * network = [networks objectAtIndex:iii];
        
        BOOL isSuccess;
        
        isSuccess = [currentInterface associateToNetwork:network password:password error:nil];
       
        if(NO == isSuccess)
            return -6;
        
    }/*@autoreleasepool*/
    
    return 0;
}/*ConnectToTargetWifiSSID*/







Connect to a Specified Wifi Router in Windows, by C



      For my feeble brain, it made me exhausted to forage a example code which is on switching/connecting  to specified wifi router. I post the code which I have sorted out. I will explain those windows api I have used.

     For use the code , you should download the windows SDK . Add that  the SDK's header path (default be C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Include ) in include path; and add SDK's libraries path (default be C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Lib) in libraries path; and add wlanapi.lib in additional dependencies.



The  code be :


#include <winsock2.h>
#include <Wlanapi.h>

#include <iphlpapi.h>

#include <stdio.h>

#pragma warning(disable:4996) /*fuss sprintf*/

#define SSID_MAX_LEN      (32)




int ConnectToTargetWifiSSID(char *pSSIDName, char *pPassword)
{
 DWORD dwVersion; 
#if(0)
 DWORD dwMajorVersion;
 dwVersion = 0 = dwMajorVersion;

    dwVersion = GetVersion();
 dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));

 DWORD dwClientVersion;
 dwClientVersion = ( dwMajorVersion >= 6) ?  2 : 1 ;  /*vista or latter*/

#endif 

 DWORD result;
 HANDLE iWifiHandle;

 PWLAN_INTERFACE_INFO_LIST iAvailableInterfaces;
 PWLAN_AVAILABLE_NETWORK_LIST availableNetworkList;

 GUID iInterfaceGuid;

 int isHavingProfile;
 
 char authentication[64];
 char encryption[64];
 int isOpenedAP;
 unsigned int i;
 unsigned int iii;


 WLAN_CONNECTION_PARAMETERS connParam;


 iWifiHandle = NULL;
 iAvailableInterfaces = NULL;
 availableNetworkList = NULL;

 
 /*part zero : one a wlan handle*/
 result = WlanOpenHandle(WLAN_API_VERSION_1_0,NULL,&dwVersion, &iWifiHandle);

 if(NULL != iWifiHandle)
 {   
   /*get wireless network card*/
   result = WlanEnumInterfaces(iWifiHandle, NULL, &iAvailableInterfaces);

   if(ERROR_SUCCESS == result && iAvailableInterfaces->dwNumberOfItems > 0)
   {
    /*chose the zeroth one*/ 
    iInterfaceGuid = iAvailableInterfaces->InterfaceInfo[0].InterfaceGuid;
   }
   else
   {
    /*no wireless card*/ 
    result = -2;
    goto Exit_ConnectToTargetSSID;
   }
   
 }
 else
 {
  result = -1;
  goto Exit_ConnectToTargetSSID;
 }/*if NULL != iWifiHandle*/




 /*part one: scan available wifi routers(SSID)*/ 
 result= WlanGetAvailableNetworkList(iWifiHandle, &iInterfaceGuid, 
  WLAN_AVAILABLE_NETWORK_INCLUDE_ALL_ADHOC_PROFILES, NULL, &availableNetworkList);


 if(ERROR_SUCCESS != result)
  return -3;

 isHavingProfile = FALSE;
 isOpenedAP = FALSE;
 iii = -1;

 memset(&authentication[0], 0, 64);
 memset(&encryption[0], 0, 64);

 if( 0 == availableNetworkList->dwNumberOfItems)
 {
  /*on wifi router has been found*/
  result = -4;
  goto Exit_ConnectToTargetSSID;
 }/*if 0 < wifiList->dwNumberOfItems*/ 


 for(i = 0; i < availableNetworkList->dwNumberOfItems; i++)
 {
         DWORD flag;

   printf("SSID:\t\t\t%s\nSIGNAL:\t\t\t%d\n",
                availableNetworkList->Network[i].dot11Ssid.ucSSID,
                availableNetworkList->Network[i].wlanSignalQuality);
   
  

        printf("SECURITY:\t\t");
        switch(availableNetworkList->Network[i].dot11DefaultAuthAlgorithm)
        {
                case DOT11_AUTH_ALGO_80211_OPEN:
     printf("OPEN\n");
     break;
                case DOT11_AUTH_ALGO_80211_SHARED_KEY:
                    printf("WEP\n");
                break;
                     
                case DOT11_AUTH_ALGO_WPA:
                case DOT11_AUTH_ALGO_WPA_PSK:
                case DOT11_AUTH_ALGO_WPA_NONE:
                    printf("WPA\n");
                break;

                case DOT11_AUTH_ALGO_RSNA:
                case DOT11_AUTH_ALGO_RSNA_PSK:
                    printf("WPA2\n");
                break;

                default:
                    printf("UNKNOWN\n");
                break;
        }

  printf("encryption:\t\t");

  switch(availableNetworkList->Network[i].dot11DefaultCipherAlgorithm)
  {
       case DOT11_CIPHER_ALGO_NONE:
     printf("NONE\n");
     break;

    case DOT11_CIPHER_ALGO_WEP40:
     printf("WEP40\n");
    break;

    case DOT11_CIPHER_ALGO_TKIP:
     printf("TKIP\n");
    break;

    case DOT11_CIPHER_ALGO_WEP104:
     printf("WEP104\n");
    break;

    case DOT11_CIPHER_ALGO_CCMP:
     printf("CCMP\n");
    break;

                default:
                    printf("UNKNOWN\n");
                break;
  }/*switch*/

  
  flag = availableNetworkList->Network[i].dwFlags;

  if(flag & WLAN_AVAILABLE_NETWORK_CONNECTED)
   printf("\t NOTE : Current connecting\n");

  if(flag & WLAN_AVAILABLE_NETWORK_HAS_PROFILE)
   printf("\t NOTE : WLAN_AVAILABLE_NETWORK_HAS_PROFILE\n");

  if(flag & WLAN_AVAILABLE_NETWORK_CONSOLE_USER_PROFILE)
   printf("\t NOTE : WLAN_AVAILABLE_NETWORK_CONSOLE_USER_PROFILE\n");
        printf("\n");
 }/*for */

 

 /*part two: save target SSID propertis*/  
 for(i = 0; i < availableNetworkList->dwNumberOfItems; i++)
 {

  if(0 == strncmp(pSSIDName, (char*)availableNetworkList->Network[i].dot11Ssid.ucSSID , SSID_MAX_LEN))
  {

   if( WLAN_AVAILABLE_NETWORK_CONNECTED & availableNetworkList->Network[i].dwFlags)
   {    
    printf("%s is current connecting!!\n", pSSIDName);
    result = 1;
    goto Exit_ConnectToTargetSSID;
   }/*if*/

   iii = i;


   if(WLAN_AVAILABLE_NETWORK_HAS_PROFILE  & availableNetworkList->Network[i].dwFlags)
    isHavingProfile = TRUE;

   /*list the target SSID properties*/

   switch(availableNetworkList->Network[i].dot11DefaultAuthAlgorithm)
   {
   case DOT11_AUTH_ALGO_80211_OPEN:
    sprintf(&authentication[0], "OPEN");
    break;
   case DOT11_AUTH_ALGO_80211_SHARED_KEY:
      sprintf(&authentication[0], "WEP");
   break;
                 
   case DOT11_AUTH_ALGO_WPA:
   case DOT11_AUTH_ALGO_WPA_PSK:
   case DOT11_AUTH_ALGO_WPA_NONE:
    sprintf(&authentication[0], "WPAPSK");
   break;

   case DOT11_AUTH_ALGO_RSNA:
   case DOT11_AUTH_ALGO_RSNA_PSK:
    sprintf(&authentication[0], "WPA2PSK");
   break;

   default:
    sprintf(&authentication[0], "UNKNOWN");
   break;
   }/*switch dot11DefaultAuthAlgorithm*/

   switch(availableNetworkList->Network[i].dot11DefaultCipherAlgorithm)
   {
    case DOT11_CIPHER_ALGO_NONE:
     sprintf(&encryption[0], "NOEN");
    break;

    case DOT11_CIPHER_ALGO_TKIP:
     sprintf(&encryption[0], "TKIP");
    break;

    case DOT11_CIPHER_ALGO_CCMP:
     sprintf(&encryption[0], "AES");
    break;


                default:
                    sprintf(&encryption[0], "WEP");
                break;
   }/*/*switch dot11DefaultCipherAlgorithm*/
   
   break; 
  }/*if 0 == strncmp(pSSIDName, (char*)availableNetworkList->Network[i].dot11Ssid.ucSSID , SSID_MAX_LEN)*/

 }/*for i*/


 if(-1 == iii)
 {
  /*target router could not found */
  result = -5;
  goto Exit_ConnectToTargetSSID;
 }/*if */
  
 
 /*part there, set XML profile*/
 if(FALSE == isHavingProfile)
 {
  /*if current computer has never connected to target router..*/

  wchar_t profileXMLUnicode[4096];
  char buff[4096];
  
  DWORD reasonCode;

  char profileTemplateXML[] = "<?xml version=\"1.0\"?>" \
 "<WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\">"\
 " <name>%s</name>" \
 "       <SSIDConfig> " \
 "                <SSID>" \
 "                        <name>%s</name>"\
 "                </SSID>"\
 "        </SSIDConfig>"\
 "        <connectionType>ESS</connectionType>"\
 "        <connectionMode>auto</connectionMode>"\
 "        <MSM>"\
 "                <security>"\
 "                        <authEncryption>"\
 "                                <authentication>%s</authentication>"\
 "                                <encryption>%s</encryption>"\
 "                                <useOneX>false</useOneX>"\
 "                        </authEncryption>"\
 "                        <sharedKey>"\
 "                                <keyType>passPhrase</keyType>"\
 "                                <protected>false</protected>"\
 "                                <keyMaterial>%s</keyMaterial>"\
 "                        </sharedKey>"\
 "                </security>" \
 "        </MSM>" \
 "</WLANProfile>" ;


  reasonCode = 0;
    
  sprintf(buff, profileTemplateXML, availableNetworkList->Network[iii].dot11Ssid.ucSSID, 
   availableNetworkList->Network[iii].dot11Ssid.ucSSID, 
   &authentication[0], &encryption[0], pPassword);

  /*Covert ansi to unicode*/ 
  MultiByteToWideChar(CP_ACP, 0, &buff[0], -1, &profileXMLUnicode[0], 4096);

  result = WlanSetProfile(iWifiHandle, &iInterfaceGuid, 0,  &profileXMLUnicode[0], 
   NULL, TRUE, NULL, &reasonCode);

  wprintf( L"%s", profileXMLUnicode); 

  if(ERROR_SUCCESS != result)
  {
   result = -6;
   goto Exit_ConnectToTargetSSID;
  }/*if */
 }
 else
 {
  /*if current computer had connected to target router, and remember who it is ...*/
  DWORD dwFlags;
  DWORD dwGrantedAccess;
  LPWSTR xml;
  result = WlanGetProfile(iWifiHandle, &iInterfaceGuid, 
   availableNetworkList->Network[iii].strProfileName, NULL, &xml ,&dwFlags,&dwGrantedAccess);
  wprintf( L"%s", xml);  
 }/*if FASLSE == isHavingProfile*/

 
 /*part four, connect to target ssid */

 connParam.pDot11Ssid= NULL;
 connParam.strProfile= availableNetworkList->Network[iii].strProfileName;

 connParam.wlanConnectionMode = wlan_connection_mode_profile;
 connParam.pDesiredBssidList=NULL;

 connParam.dot11BssType= availableNetworkList->Network[iii].dot11BssType;
 connParam.dwFlags = 0;

 //wprintf( L"%s", &iInterfaceGuid,wifiList->Network[iii].strProfileName);
 result = WlanConnect(iWifiHandle, &iInterfaceGuid, &connParam, NULL); 
 
 if(ERROR_SUCCESS != result)
  result = -7;
  
 

Exit_ConnectToTargetSSID:

 if(NULL != availableNetworkList)
  WlanFreeMemory(availableNetworkList);

 if(NULL != iAvailableInterfaces)
  WlanFreeMemory(iAvailableInterfaces);

 if(NULL != iWifiHandle)
  WlanCloseHandle(iWifiHandle, NULL);

 return result;
}/*ConnectToTargetWifiSSID*/


int main(int argc, char *argv[])
{
 ConnectToTargetWifiSSID("GAIGER TOTO", "qwertyui");
 return 0;
}/*main*/


           you should modify the function agruments pSSIDName(I used "GAIGER TOTO") and pPassword (I used "qwertyui") as your ssid/password. To test the code, you had better let your computer forget the information of target ssid, and disconnnect your wireless network. Otherwise,  the code would display "be current conncting" or the variable "isHavingProfile" be TRUE always.

In "manage wireless networks" of windows, you could set/delete it.