E-mail: broyer@telus.net
Code Samples
Home
Hobbies
Favorites
Downloads
Code samples
C++ Samples
(Click title to see the sample code)
Sample to read a file into a vector
// Note: this program assumes that precompiled headers are turned off #include <string> #include <vector> #include <fstream> #include <iostream> using namespace std; // simplifies things std::string to string int main(int argc, char* argv[]) { if(argc < 2) { cout << " Usage: " << argv[0] << " <put filename here>" << endl; return 1; } vector<string> file; string line; file.clear(); ifstream infile(argv[1],ios_base::in); while(getline(infile,line,'\n')) { file.push_back(line); } cout << "Read " << file.size() << " lines." << endl; return 0; }
Semaphore sample
// partial sample, I may create a class for this later // create a semaphore object simple single lock example // param 1: security object // param 2: initial count // param 3: max count // param 4: name this is usefull for multiple apps HANDLE g_hCritical = CreateSemaphore(NULL,1,1,NULL); // grab a semaphor object to prevent collisions if( WaitForSingleObject(g_hCritical,1000) == WAIT_TIMEOUT ) { return 0; } // do stuff here // release the semaphor for other parts of the code ReleaseSemaphore(g_hCritical, 1, NULL); // close the handle when finished using it CloseHandle(g_hCritical);
Find window sample
// partial code int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine,int nCmdShow) { // ... // see if this program is already running HWND hWnd = FindWindow(szWindowClass,szTitle); // if not NULL it means the window was found if(hWnd) { // send a Left-button-double-click message to the window SendMessage(hWnd,WM_TRAY,0,WM_LBUTTONDBLCLK); // just exit this program with return code of zero return 0; } // ... } // WinMain
thread sample
#include <windows.h> #include <string.h> #include <stdio.h> #include <process.h> #include "resource.h" #define MAX 5000 LRESULT CALLBACK WindowFunc(HWND, UINT, WPARAM, LPARAM); unsigned __stdcall MyThread1(void * param); unsigned __stdcall MyThread2(void * param); char szWinName[] = "MyWin"; char str[255]; DWORD Tid1,Tid2; HANDLE hSema; // -------------------------------------------------- // Using events with threads // -------------------------------------------------- // HANDLE CreateEvent(LPSECURITY_ATTRIBUTES lpSecAttr, // BOOL bManual, // BOOL bInitial, // LPSTR lpszName); // BOOL SetEvent(HANDLE hEventObject); // BOOL ResetEvent(HANDLE hEventObject; // -------------------------------------------------- // Use this structure to check for an event // -------------------------------------------------- // if(WaitForSingleObject(hEvent,10000)==WAIT_TIMEOUT) // { // MessageBox((HWND)param, "Time out Thread 1", // "Semaphore Error", MB_OK); // return 0; // } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInst, LPSTR lpszArgs, int nWinMode) { HWND hWnd; MSG msg; WNDCLASSEX wcl; HANDLE hAccel; wcl.cbSize = sizeof(WNDCLASSEX); wcl.hInstance = hInstance; wcl.lpszClassName = szWinName; wcl.lpfnWndProc = WindowFunc; wcl.style = 0; wcl.hIcon = LoadIcon(NULL, IDI_APPLICATION); wcl.hIconSm = LoadIcon(NULL, IDI_APPLICATION); wcl.hCursor = LoadCursor(NULL, IDC_ARROW); wcl.lpszMenuName = "ThreadMenu"; wcl.cbClsExtra = 0; wcl.cbWndExtra = 0; wcl.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); if(!RegisterClassEx(&wcl)) { return 0; } hWnd = CreateWindow(szWinName, "Demonstration Threads", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, HWND_DESKTOP, NULL, hInstance, NULL); hAccel = LoadAccelerators(hInstance, "ThreadAccel"); ShowWindow(hWnd, nWinMode ); UpdateWindow(hWnd); while(true) { if(PeekMessage(&msg,NULL,0,0,PM_REMOVE)) { if(msg.message == WM_QUIT) { break; // loop } if(!TranslateAccelerator(hWnd, (HACCEL)hAccel, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } else { // add timing code here } } return 0; } LRESULT CALLBACK WindowFunc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int response; switch(message) { case WM_CREATE: hSema = CreateSemaphore(NULL, 1,1,NULL); break; case WM_COMMAND: switch(LOWORD(wParam)) { case IDM_THREAD: _beginthreadex(NULL, 0, MyThread1,(LPVOID)hWnd, 0, (unsigned*)& Tid1); _beginthreadex(NULL, 0, MyThread2,(LPVOID)hWnd, 0, (unsigned*)& Tid2); break; case IDM_EXIT: response = MessageBox(hWnd,"Quit the Program?","Exit", MB_YESNO); if(response == IDYES) { PostQuitMessage(0); } break; case IDM_HELP: MessageBox(hWnd, "F1: Help\nF2: Demonstrate Threads","help", MB_OK); break; } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd,message,wParam,lParam); } return 0; } unsigned __stdcall MyThread1(void* param) { int i; HDC hdc; if(WaitForSingleObject(hSema,10000)==WAIT_TIMEOUT) { MessageBox((HWND)param, "Time out Thread 1", "Semaphore Error", MB_OK); return 0; } for( i=0; i<MAX; i++ ) { if( i == MAX/2 ) { ReleaseSemaphore(hSema, 1, NULL); if(WaitForSingleObject(hSema,10000)==WAIT_TIMEOUT) { MessageBox((HWND)param, "Time out Thread 1", "Semaphore Error", MB_OK); return 0; } } sprintf(str, "Thread 1: loop # %5d ", i); hdc = GetDC((HWND) param); TextOut(hdc, 1, 1, str, strlen(str)); ReleaseDC((HWND) param, hdc); } ReleaseSemaphore(hSema, 1, NULL); return 0; } unsigned __stdcall MyThread2(void* param) { int i; HDC hdc; if(WaitForSingleObject(hSema,10000)==WAIT_TIMEOUT) { MessageBox((HWND)param, "Time out Thread 1", "Semaphore Error", MB_OK); return 0; } for(i=0; i<MAX; i++) { if(i == MAX/2) { ReleaseSemaphore(hSema, 1, NULL); if(WaitForSingleObject(hSema,10000)==WAIT_TIMEOUT) { MessageBox((HWND)param, "Time out Thread 1", "Semaphore Error", MB_OK); return 0; } } sprintf(str, "Thread 2: loop # %5d ", i); hdc = GetDC((HWND) param); TextOut(hdc, 1, 20, str, strlen(str)); ReleaseDC((HWND) param, hdc); } ReleaseSemaphore(hSema, 1, NULL); return 0; }
ostrstream sample
// partial example #include <iostream> #include <strstream> using namespace std; // snip ostrstream message; int i = 1; // this is required to allocate space for the string message << ends; // ----------------------------------------------------------------- // in order to reuse the strstream object you must do the following: // ----------------------------------------------------------------- message.clear(); // clear any error in the stream message.rdbuf()->freeze(0); // unlock the stream if its locked message.seekp(0); // puts the pointer back to the start // ----------------------------------------------------------------- // "ends" puts a zero at the end of the str // if you need a new line use "endl" as well as "ends" // eg. message << i << " " << "some text" // << endl << ends; message << "Name" << i << ends; // Warning! str() freezes the stream cout << i << " " << message.str(); // sample output: // 1 name1 // snip
stream notes
// partial example #include <iostream> #include <iomanip> using namespace std; // to preserve a streams settings one way is to save the // settings and restore them later // -=-=- save the settings -=-=- streamsize oldWidth = cout.width(); _Elem oldFill = cout.fill(); ios_base::fmtflags oldFlags = cout.flags(); streamsize oldPrecision = cout.precision(); cout << setw(30) << setfill('*') << name << endl; // -=-=- restore the settings -=-=- cout.width(oldWidth); cout.fill(oldFill); cout.flags(oldFlags); cout.precision(oldPrecision); // if you wish to show the words for bools, // i.e., 'true' or 'false'; instead of 1 or 0 // use alphabool cout << alphabool << true // output: true << noboolalpha << false // output: 0 << endl; // to show the + infront of non-negative values use this cout << showpos << 99 // output: +99 << noshowpos << 99 // output: 99 << endl; // to ignore white space on inputs use this // always use setw() or cin.width() to prevent buffer overflows cin >> skipws >> setw(30) >> value; // to change the base use these // note only one can be used at a time cout << dec << 99 << hex << 99 << oct << 99 << endl; // to change the alignment use these // note only one can be used at a time cout << left << setw(30) << "test" << endl; cout << right << setw(30) << "test" << endl;