Wednesday, April 10, 2013

Simulating Key Events in C using XWindow Programming

lets write a small program, where we can simulate ALT+F4(close) key functionality in C using Xwindow System Programming.

// FileName: CloseSimulation.c

#include <X11/Xlib.h>
#include  <X11/keysym.h>
#include  <X11/extensions/XTest.h>
#include  <stdio.h>
void main()
{
    Display *display;
    unsigned int keycode[2];
    display = XOpenDisplay(NULL);
    //getting Alt and F4 key codes
    keycode[0] = XKeysymToKeycode(display, XK_Alt_L);
    keycode[1] = XKeysymToKeycode(display, XK_F4);
    //Pressing Alt
    XTestFakeKeyEvent(display, keycode[0], True, 0);
    //Pressing F4
    XTestFakeKeyEvent(display, keycode[1], True, 0);
    //Releasing F4
    XTestFakeKeyEvent(display, keycode[1], False, 0);
    //Releasing Alt
    XTestFakeKeyEvent(display, keycode[0], False, 0);
    XFlush(display);
}

To Run: gcc -lX11 -lXtst CloseSimulation.c
             ./a.out

Output: It simply simulates Alt+F4 and closes the terminal where you are running this program.

To Know executing commands through C program Click Here

Tuesday, April 9, 2013

Generic Functions In C Lanuguage

Most of the people use macros in C language to define constants only. But the powerful feature of macro is, its ability to generate generic functions. Till now most of the people have seen generic functions in object oriented programming only. In C we can create generic functions using macro. A generic function is a function that is declared with type parameters. When called, actual types are used instead of the type parameters.
         
 Lets see the following example, where i am creating a generic function to find minimum number, out of 2 numbers using a macro.

// File Name: genericFunction.c

#include<stdio.h>
#define MIN(FunName, Dtype) \
        Dtype FunName(Dtype x, Dtype y)\
             { return x>y?y:x; }\

MIN(int_min, int)
MIN(float_min, float)

void main()
{
  int k;
  float l;
  k = int_min(5, 6);
  l = float_min(7.0, 6.9);
  printf("\n Min Integer is: %d", k);
  printf("\n Min float is: %f", l);
}

To Run: gcc  genericFunction.c
              ./a.out

In the above program i am using same macro to generate definitions for int_min, float_min functions, that means i have created a generic function for the same.

MIN(int_min, int) can be expanded as int int_min(int, int)  and
MIN(float_min, float) can be expanded as float float_min(float, float).

Thursday, April 4, 2013

Optimization Of Nested For Loops

Hi Guys... In this post i am going to explain you that, how to write optimized nested for loops. Consider the following two nested for loops.

// Nested for loop-1
   for(a=0; a<20; a++)
   for(b=0; b<100; b++) 

// Nested for loop-2 
   for(c=0; c<100; c++)
   for(d=0; d<20; d++) 

 Both nested for loops gives same kind of functionality and the code in both nested for loops execute same number of times. Now let me ask one question :-)

which nested for loop is faster, loop-1 or loop-2?

You must be thinking, both execute in same time period. but actually not.

For Loop-1:

      
Number of post increment operations are: 20 X 100 + 20 = 2020;
       Number of comparisons are: [20 X 100 + 20] + 20 = 2040

For Loop-2:

     
Number of post increment operations are: 100 X 20 + 100 = 2100;
       Number of comparisons are: [100 X 20 + 100] + 100 = 2200

Conclusion:

If we compare both nested for loops w.r.t number of increment operations and comparisons, loop-1 is faster than loop-2. So, whenever we write nested for loops, it is better to choose the for loop, whose MAX_LIMIT is less than other as the first for loop.

for(a=0; a<MAX_LIMIT_A; a++)
for(b=0; b<MAX_LIMIT_B; b++)

Where MAX_LIMIT_A < MAX_LIMIT_B

Program to Test:

// File: loopCompare.c

#include<stdio.h>
void main()
{
  int comp_firstloop=0, incre_firstloop=0, comp_secondloop=0, incre_secondloop=0;
  int a, b, c, d;
   
  for(a=0; (++comp_firstloop) && a<20; a++, ++incre_firstloop)
  for(b=0; (++comp_firstloop) && b<100; b++, ++incre_firstloop);

  for(c=0; (++comp_secondloop) && c<100; c++, ++incre_secondloop)
  for(d=0; (++comp_secondloop) && d<20; d++, ++incre_secondloop);
  
  printf("\n #No. of Increment Operatiosn of 1st Nested For loop: %d", incre_firstloop);
  printf("\n #No. of comparison Operations of 1st Nested For loop: %d", comp_firstloop);

  printf("\n #No. of Increment Operations of 2nd Nested For loop: %d", incre_secondloop);
  printf("\n #No. of comparison Operations of 2nd Nested For loop: %d", comp_secondloop);
}

To Run:
gcc loopCompare.c
               ./a.out

OutPut:
 
#No. of Increment Operations of 1st Nested For loop: 2020
 #No. of comparison Operations of 1st Nested For loop: 2041
 #No. of Increment Operations of 2nd Nested For loop: 2100
 #No. of comparison Operations of 2nd Nested For loop: 2201

Thursday, March 28, 2013

Getting FILE information Via Stat in C Language

We know that Linux/Unix file system stores information for every file. Some of the information can be obtain by stat - A Unix system call. This system call is defined in < sys/stat.h> header file.

stat structure has the following fields.

struct stat {
    dev_t     st_dev;     /* ID of device containing file */
    ino_t     st_ino;     /* inode number */
    mode_t    st_mode;    /* protection */
    nlink_t   st_nlink;   /* number of hard links */
    uid_t     st_uid;     /* user ID of owner */
    gid_t     st_gid;     /* group ID of owner */
    dev_t     st_rdev;    /* device ID (if special file) */
    off_t     st_size;    /* total size, in bytes */
    blksize_t st_blksize; /* blocksize for file system I/O */
    blkcnt_t  st_blocks;  /* number of 512B blocks allocated */
    time_t    st_atime;   /* time of last access */
    time_t    st_mtime;   /* time of last modification */
    time_t    st_ctime;   /* time of last status change */
};


Now lets write a small program to get the file information using stat system call.

// File name Stat.c

#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
int main(int argc, char **argv)
{
    if(argc != 2)   
        return 1;

    struct stat fileInfo;
    // getting file information into fileInfo using stat
    if(stat(argv[1],&fileInfo) < 0)   
        return 1;

    // printing file information
    printf("Information for %s\n",argv[1]);
    printf("---------------------------------------------------\n");
    printf("File Size: \t\t%d bytes\n",fileInfo.st_size);
    printf("Number of Links: \t%d\n",fileInfo.st_nlink);
    printf("File inode: \t\t%d\n",fileInfo.st_ino);

    // S_ISDIR, S_IRUSR,....are marcos
    printf("File Permissions Are: \t");
    printf( (S_ISDIR(fileInfo.st_mode)) ? "d" : "-");
    printf( (fileInfo.st_mode & S_IRUSR) ? "r" : "-");
    printf( (fileInfo.st_mode & S_IWUSR) ? "w" : "-");
    printf( (fileInfo.st_mode & S_IXUSR) ? "x" : "-");
    printf( (fileInfo.st_mode & S_IRGRP) ? "r" : "-");
    printf( (fileInfo.st_mode & S_IWGRP) ? "w" : "-");
    printf( (fileInfo.st_mode & S_IXGRP) ? "x" : "-");
    printf( (fileInfo.st_mode & S_IROTH) ? "r" : "-");
    printf( (fileInfo.st_mode & S_IWOTH) ? "w" : "-");
    printf( (fileInfo.st_mode & S_IXOTH) ? "x" : "-");
    printf("\n");

    return 0;
}


To Run: gcc Stat.c
              ./a.out Stat.c  // giving Stat.c file name as input

Out Put: 
Information for Stat.c
----------------------------------------
File Size:         1256 bytes
Number of Links:     1
File inode:         2367639
File Permissions Are:     -rw-r--r--

Tuesday, March 19, 2013

Redirection Using dup & dup2

dup and dup2 are basic I/O Unix system calls. Following program shows a sequence of dup operations that temporarily redirect the standard out put to "stdout.log" file. If we then want to use the original standard output we can duplicate that using dup2 system call, with help of already saved file descriptor fd.


// File Name: redirect.c

 #include <stdio.h>

   void main()
    {
        // File descriptor        

         int    fd;

        // This object is used to specify a position within a file     
         fpos_t pos;

        printf("\n stdout is normal ");
        fflush(stdout);

        //Getting current position in stream
        fgetpos(stdout, &pos);

        // Redirecting standard output to stdout.log file
        fd = dup(fileno(stdout));
        freopen("stdout.log", "w", stdout);

        fun();
        fflush(stdout);

        // Standard output is restoring to original settings
        dup2(fd, fileno(stdout));
        close(fd);
        clearerr(stdout);
        fsetpos(stdout, &pos);

        printf("\n stdout is normal again\n");
    }

    fun()
    {
    printf("stdout in f() is redirected to this file(stdout.log)");
    }

To run : gcc redirect.c
              ./a.out

After running above 2 commands you can see a file named stdout.log in your current directory with content "stdout in f() is redirected to this file(stdout.log)".

Monday, March 11, 2013

Run Applications Through C Program

Some times our project demands to start a particular application through C program. Here i will show you how to do that.

To start a application through C program, we can use a system call called execlp, which comes under exec family of UNIX system calls.

// Compiler: GCC
//File Name: execute.c
#include <stdio .h>
#include <unistd .h>
void main()
{
pid_t pid = fork();
switch (pid) {
       case 0:
        execlp("/bin/sh", "sh", "-c", "firefox http://umencs.blogspot.in", NULL);
            //execlp("/bin/sh", "sh", "-c", "gedit", NULL);
            //execlp("/bin/sh", "sh", "-c", "nautilus", NULL);
       case -1:
        printf("Error: can't execute command: fork() failed\n");
       }
}

In execlp system call -c option is used to read commands from the command_string operand instead of from the standard input.

To run above program use following commands
$gcc execute.c
$./a.out

the above program will open  http://umencs.blogspot.in in Firefox.


Building GUI using GtkBuilder in C Project

GLADE is a RAD(Rapid Application Development) Tool which is used for quick and easy development of GUI for GTK+ toolkit and GNOME Desktop environment.

GUI designed by glade, can be saved in XML file (it can be saved in .C or .glade file also). Using GtkBuilder (A GTK+ object), this GUI xml can be loaded by applications dynamically.

By using GtkBuilder, Glade XML files can be used in numerous programming languages including C, C++, C#, Vala, Java, Perl, Python and others.
Building GUI using GtkBuilder in C-Program:

Assume we have designed a GUI using glade, which is saved as gem.glade /gem.xml /gem.c. Irrespective of their extensions all these files contains XML format strings/tags only, which contains information to build GUI. For example, if we consider gem.c file, it contains the code as shown below
gem.c
********

Now we send gui_buffer (see above code) as a parameter to GtkBuilder, which builds required GUI of our application. To access gui_buffer in any file make a declaration

extern const char *gui_buffer;

//Code to build gui by GtkBuilder
 try {
        widgets = Gtk::Builder::create_from_string(gui_buffer);
    } catch (Gtk::BuilderError &e) {
        printf("Error building GUI: %s\n", e.what().c_str());
        exit(EXIT_FAILURE);
    }