Showing posts with label c. Show all posts
Showing posts with label c. Show all posts

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

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);
    }