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

The project, “Library Management in C,” is larger and more complex than my other projects, such as the Quiz game, Contact Management, and Personal Diary Management. In this project, I have implemented a variety of techniques and features, including Admin and Student modes, user security, reading and writing CSV files, and many others. This project will provide you with numerous insights. If you’re aiming for the highest grade in your project/lab assignment, I recommend following this project.

The main objective of this project is to introduce you to the following techniques and features:
  • Breaking down the application and representing it with a flowchart
  • Creating a function call stack diagram
  • Creating an application menu and navigating in and out of the user screens
  • Implementing a user login system using a username and password
  • Reading and writing data from and into a CSV file
  • Dynamic memory allocation to create dynamic array
  •  Add and delete data from dynamic memory array.
  • Performing CRUD (Create, Read, Update, and Delete) operations in C file handling
  • Implementing many utility functions such as converting an integer to a string, a string to an integer, hiding password by displaying asterisks
In this article, I will not explain each and every function of the application. The style of creating a user menu and the technique of switching in and out of the screens, C file handling is the same as in other projects. Here, I will explain the flowchart, function call stack diagram, and major functions such as the login system, reading and writing CSV files, and other major and complex functions.

You can download the final version of the application from Github Download from Github.

I have divided this project into 4 parts. Also, please follow YouTube video to get more details about the project.