Saturday, March 19, 2011

Digital clock implementation in C using time.h header

This sample application is the implementation of the clock() function available in time.h header. The time function is very useful and necessary. Some of the examples of usage of time function are:
  • Security applications might need to update the security keys every one minute or more. 
  • You may need to write a function to send files to the remote server every one minute or extract files from the server every 15 minutes. 
and many more.

I have created a simple digital clock to show you the implementation of clock() function. The sample code given below is written in C using codeblocks IDE on windows.

#include <stdio.h>
#include <time.h>         //this is header file for time
#include <windows.h>

COORD coord = {0, 0};
void gotoxy (int x, int y)
{
    coord.X = x;
    coord.Y = y; // X and Y coordinates
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

int main()
{

    long i = 0;                      /* Loop counter              */
    clock_t now = 0;                 /* Holds initial clock time  */
    int interval = 1;                /* Seconds interval for o/p  */
    int elapsed = 0;
    int min=0,MIN=0,hrs=0,sec=0;
    int d=0,f=0;
    now = clock(); /* Get current clock time    */
    
    for(i = 0L ;  ; i++)
    {
        elapsed = (clock()-now)/CLOCKS_PER_SEC;

        if(elapsed>=interval)
        {
            interval += 1;
            if(elapsed%60==0)
            {
                min=elapsed/60;
                d=60*min;
                if(min%60==0)
                {
                    hrs=min/60;
                    f=60*hrs;
                }
            }
            sec=elapsed-d;
            MIN=min-f;
            if(hrs<10)
            {
                gotoxy(2,4);
                printf("0%d",hrs);
            }
            else
            {
                gotoxy(2,4);
                printf(":%d",hrs);
            }
            if(min<10)
            {
                gotoxy(4,4);
                printf(":0%d",MIN);
            }
            else
            {
                gotoxy(4,4);
                printf(":%2d",MIN);
            }

            if(sec<10)
            {
                gotoxy(7,4);
                printf(":0%d",sec);
            }
            else
            {
                gotoxy(7,4);
                printf(":%2d",sec);
            }
            gotoxy(7,7);
            printf("%dhrs:%dmin:%dsec",hrs,MIN,sec);
        }
    }

    return 0;
}

Resize and Move Console Window in C/C++ using windows function

This is another article related to the window.h library function. Here I will take you through resizing the console window and moving it on the screen at the desire position. Using window.h library function is the only option to control console windows if you are not using third-party graphics library. Resizing and moving console window function is useful if your application needs to create multiple windows and position it as per requirement. 
Note: Below sample C code works only in the windows environment.

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

HWND WINAPI GetConsoleWindowNT(void)
{
    //declare function pointer type
    typedef HWND WINAPI(*GetConsoleWindowT)(void);
    //declare one such function pointer
    GetConsoleWindowT GetConsoleWindow;
    //get a handle on kernel32.dll
    HMODULE hk32Lib = GetModuleHandle(TEXT("KERNEL32.DLL"));
    //assign procedure address to function pointer
    GetConsoleWindow = (GetConsoleWindowT)GetProcAddress(hk32Lib
    ,TEXT("GetConsoleWindow"));
    //check if the function pointer is valid
    //since the function is undocumented
    if(GetConsoleWindow == NULL){
        return NULL;
    }
    //call the undocumented function
    return GetConsoleWindow();
}
int main()
{
    HWND hWnd=GetConsoleWindowNT();
    MoveWindow(hWnd,1230,600,300,200,TRUE);
}
I suggest you to test the parameters values of the function MoveWindow because the maximum value depends upon the size of the laptop or monitor screen.

Change console windows background color in C

In my earlier article changing text color in codeblock and text background color of console, I had provided a sample source code to change text color and text background color using windows.h library function. Similarly, we can also change console windows background color using windows.h library function. Here, I have shared a sample source code to change the console windows background color. The sample program is written in C.

#include <windows.h>          //header file for windows
#include <stdio.h>

void ClearConsoleToColors(int ForgC, int BackC);
int main()
{
    ClearConsoleToColors(0,1);
    Sleep(1000);
    return 0;
}
void ClearConsoleToColors(int ForgC, int BackC)
{
    WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);
    //Get the handle to the current output buffer...
    HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
    //This is used to reset the carat/cursor to the top left.
    COORD coord = {0, 0};
    //A return value... indicating how many chars were written
    //   not used but we need to capture this since it will be
    //   written anyway (passing NULL causes an access violation).
    DWORD count;

    //This is a structure containing all of the console info
    // it is used here to find the size of the console.
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    //Here we will set the current color
    SetConsoleTextAttribute(hStdOut, wColor);
    if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
    {
        //This fills the buffer with a given character (e.g 32=space).
        FillConsoleOutputCharacter(hStdOut, (TCHAR) 32
        , csbi.dwSize.X * csbi.dwSize.Y, coord, &count);

        FillConsoleOutputAttribute(hStdOut, csbi.wAttributes
        , csbi.dwSize.X * csbi.dwSize.Y, coord, &count );
        //This will set our cursor position for the next print statement.
        SetConsoleCursorPosition(hStdOut, coord);
    }
    return;
}
You can change console windows background color by passing integer value range 0 up-to 256 in ClearConsoleToColors(int ForgC, int BackC) function.



Change text background color in C console application

Usually, console applications are black and white. However, sometimes for specific purposes, we may need to change the text background color to highlight the specific texts. Changing text background color in the console is challenging especially if you are using Codeblocks MinGW. Unlike turbo c/c++ GCC does not provide the function to change the text background color. If you want to change the text background color then we should use windows.h library function. You can find the sample code below which change text background color. The sample program is written in C utilizing windows.h library function.

#include <windows.h>         //header file for windows
#include <stdio.h>           //C standard library
void SetBackgroundColor(int BackC);
int main(){

    int i=0;
    for(i=0; i<256; i++){
        SetBackgroundColor(i);
        printf("Test Text Background Color for value i: %d\n",i);
    }
    getch();

    return 0;
}
void SetBackgroundColor(int BackC)
{
     CONSOLE_SCREEN_BUFFER_INFO csbi;
     WORD wColor = ((BackC & 0x0F) << 4) + (csbi.wAttributes & 0x0F);
     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), wColor);
     return;
}
In output program, for every 16 values (0-15, 16-32, etc) text colors will repeat. It means in this method we get only 4 bit color space i.e only 16 colors. You can change your desired text background color by passing integer value range 0 up to 15 in SetBackgroundColor() function.



Change text color in C console application

Usually, console applications are black and white. However, sometimes for specific purposes, we need to change the text color to highlight the specific values, dates, or texts. Changing text color in the console is challenging especially if you are using Codeblocks MinGW. Unlike turbo c/c++ GCC does not provide the function to change text color. If you want to change the text color to make console windows colorful then we should use windows.h library function. You can find the sample code below which change text color. The sample program is written in C utilizing windows.h library function.

#include <windows.h>         //header file for windows
#include <stdio.h>           //C standard library
void SetColor(int ForgC);
int main(){

    int i=0;
    for(i=0; i<256; i++){
        setColor(i);
        printf("Test Color Text for value i: %d\n",i);
    }
    getch();

    return 0;
}

void setColor(int ForgC){

    //We will need this handle to get the current background attribute
    WORD wColor; 
    
    HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
    
    //we use csbi for the wAttributes word.
    CONSOLE_SCREEN_BUFFER_INFO csbi; 

    if(GetConsoleScreenBufferInfo(hStdOut, &csbi)){
        //Mask out all but the background attribute
        //, and add in the foreground color
        wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
        SetConsoleTextAttribute(hStdOut, wColor);
    }
    return;
}

In output program, for every 16 values (0-15, 16-32, etc) text colors will repeat. It means in this method we get only 4 bit color space i.e only 16 colors. You can change your desired text color by passing integer value range 0 up to 15 in SetColor() function.



Thursday, March 17, 2011

gotoxy function in Codeblocks

gotoxy(int x, int y) a function available in Turbo C/C++. It is not standard C. This function is used to move the cursor on the screen to the desire location. The top left corner of the monitor is 0,0 and the bottom right corner might be any number based on the size of the screen. But today's standard C++ compiler such as Visual Studio, GCC and clang do not provide gotoxy function. However, if you are developing console applications without a third party graphic library then gotoxy function is useful to manage text alignment on the screen.

If you need similar implementation on a windows machine with GCC compiler then here is an example source code.
#include <windows.h>    //  header file for gotoxy
#include <iostream> //header file for standard input output
COORD coord= {0,0}; // this is global variable
void gotoxy(int x,int y)
{
    coord.X=x;
    coord.Y=y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}

int main()
{
    //calling these function
    int x;
    gotoxy(15,5);
    std::cout<<"1. This is item number one.";
    gotoxy(15,7);
    std::cout<<"2. This is item number two.";
    gotoxy(15,9);
    std::cout<<"3. This is item number three.";
    gotoxy(15,11);
    std::cout<<"4. This is item number four.";
    gotoxy(15,13);
    std::cout<<"5. This is item number five.";
    std::cin>>x;
    return 0;
}
Please watch the video below for detailed explanation.

Sunday, March 13, 2011

Mini project "library management" in C programming


      This is my college 1st-semester mini-project “library management “ in C programming language. This is a console application without graphics and compiled in code::block with GCC compiler. I hope it will help you to develop your own project similar project related to file handling for example “Banking “,” customer records”,” student records" etc.
I have divided my project into many functions and I will describe each of them which may help you to understand better.