Monthly Archive: November 2010

C Language Reference Resources

C Plus Plus Minus MinusThis is just a small post to list some of the references for C standard library functions:

Do you have any other resources for the C language? Please share them in the comment below.

Generating Random Numbers with C

C Plus Plus Minus Minus

Introduction

There are some standard library functions for generating random numbers in C:

  • The function rand is used for generating a pseudo-random number between 0 and RAND_MAX where RAND_MAX is defined using #define. Here is an example:
    x = rand();
  • Note that pseudo-random number means that sometimes the function will generate the same number each time the function is executed.
  • The function srand can be used to fix this issue so that it generates different random number all the time. It’s used to seed (which I think it’s the helper function) the rand function, Below is an example:
    srand(12345);

Example Code

/*

 *      random.c

 *

 *      Program to demonstrate the use of rand() and srand()

 *

 *      by Mark Virtue, 2001.

 */

#include <stdio.h>

#include <stdlib.h>



main()

{

    int     i;



    srand(time(NULL));	// Use the current system time as the seed so that it can generate different set of numbers each time the program is executed



    for (i = 0; i < 10; i++)

        printf("Random number #%2d is : %6dn", i+1, rand());	// Generating 10 random numbers. However, sometimes it will generate the same set of numbers each time the program is executed.


    fflush(stdin);

    getchar();



    return 0;

}

Questions or problems?

If you have any issue compiling and running the above code, fell free to discuss them in the comment below.

Using Standard I/O Functions

Introduction

Continue from the last post, this time I’m going to talk about the usage of standard I/O functions.

Example Code

The following code is copied from the original tutorial. It’s well documented by me. I also added and modified some places of the source code wherever GCC is mentioned in the comments.

/*

 *      average.c

 *

 *      Program to demonstrate I/O to text files

 *

 *      by Mark Virtue, 2001.

 */

 

#include <stdio.h>

#include <stdlib.h>
#include <errno.h>		// for printing out error message as required by GCC
#include <string.h>		// for strerror() to work correctly, required by GCC

#include <time.h>       // for time() and ctime()



#define FNAME   "./test123"		// Create the file in the program's folder'



/*

 *  pause()

 *

 *  Ask the user to press ENTER

 *  This function is used in conjunction with atexit()

 */

void pause()

{
	while (getchar() != 'n') {}	// Use the while loop to clear the input variable cache for GCC

    printf("nProgram ended, Press ENTER: ");

    fflush(stdin);

    getchar();

}



main()

{

    FILE    *fptr;

    int     count;

    int     number;

    int     total = 0;

    time_t  the_time;

    int     i;



    atexit(pause);



    /*

     *  First, open the text file for writing

     *  and write out the header info to it

     */

    fptr = fopen(FNAME, "w");	// w means that opening the file for writing

    if (fptr == NULL)	// In case if fopen fails to open the file

    {

        fprintf(stderr, "Could not open %s - %sn", FNAME, strerror(errno));	// errno contains the error number that is generated during the failure. It explans why the fopen failed. sys_errlist converts errno to the readable error message. Both sys_errlise and errno are the global variables.
        /*
         * Note that the the original variable sys_errlist is deprecated in GCC.
         * I used strerror() above as recommended by the warning message of GCC
         */

        exit(1);	// Exit the program since the file failed to open and nothing to execute without opening the file

    }



    /*

     *  Test to see if we can write to the file

     */

    if (fprintf(fptr, "This is the output file for the File I/O programnn") < 0)	// Try to print one line of text into the file to test its writability after the file is opened successfully

    {

        perror("Could not write to the file");	// It's the same as the above error statement. perror() writes to the stderror and output the message along with sys_errlist[errno] error message

        fclose(fptr);	// Close the file since it's unable to write to the file. It's a good practice to manually close the file once the program finishes operation with the file.

        exit(1);	// Exit the program once the file is closed

    }



    /*

     *  Write the rest of the header info, including the current time

     */

    the_time = time(NULL);	// time(NULL) is used for getting the system time

    fprintf(fptr, "ttCreated on %snn", ctime(&the_time));	// ctime() is used to print out the current time

    fputs("The numbers are:nn", fptr);



    /*

     *  Determine how many integers are to be averaged

     */

    printf("How many numbers do you want to average: ");

    scanf("%d", &count);



    /*

     *  We don't want to divide by zero if count == 0, so...

     */

    if (count == 0)

    {

        fputs("No numbers to averagen", fptr);	// Print the message to the file instead of on the screen

        fclose(fptr);	// Close the file since it doesn't have anything to average

        exit(0);	// Close the program

    }



    /*

     *  Otherwise, read all the numbers and accumulate them

     */

    for (i = 0; i < count; i++)	// Use for loop to enter all the required numbers

    {

        printf("Please enter number #%d: ", i+1);

        scanf("%d", &number);



        /*

         *  Add this integer to our total

         */

        total += number;



        /*

         *  Write the number out to the file

         */

        fprintf(fptr, "%3d: %4dn", i+1, number);

    }



    /*

     *  A final message, then close the file

     */

    fprintf(fptr, "nThe average is %fn", (float)total / count);

    fclose(fptr);



    return 0;

}

Questions or Problems?

If you have any problem compile and running above source code, please leave a comment below.

Some Useful gEdit Plugins for Developers: Part Three – Third-Party Plugins (2)

Introduction

In the last post, I listed few of the third-party plugins from the gEdit plugins page that are useful for developers. This post I’m going to list some more useful third-party plugins for development. Here is the list of previous posts in this series:

  1. Part One – Default Plugins and gedit-plugins
  2. Part Two – Third-Party Plugins (1)

The List

  • Focus Autosave (http://github.com/kassoulet/gedit-focus-autosave)
    Once this plugin is enabled, the opened documents/tabs will save automatically when switching to another window. It is very useful for testing the just written code in the web browser. What I like this plugin is that it saves all the opened documents/tabs instead of save only the current document when using the auto save feature in the default gEdit preferences.
  • Line-Spacing (http://users.tkk.fi/~otsaloma/gedit)
    When enabling this plugin, click the Configure Plugin button to set line height in pixels between each line. The plugin could be used for reading the source code by making the lines easier to read.
  • Macro (http://code.google.com/p/gedit-macro-plugin)
    This plugin reduces the code repetition by automatically enter key strokes using macro. It even has a 64-bit version. However, the plugin could store only one macro. This means that it could only store one repeatable task at a time.
  • Pair char autocompletion (http://code.google.com/p/gedit-pair-char-autocomplete/)
    This plugin gives gEdit the ability to add and override the closing brackets and quotes after typing these opening operators. It’s even better compare to the NetBeans editor. The plugin also supports ` operator which NetBeans doesn’t support. This operator is normally used within SQL statements. Including this operator, the plugin also supports the following: (), [], {}, “”, ”, and “. There is full documentation on its Google Code project page.
  • Right Pane (https://sourceforge.net/projects/gedit-rightpane/)
    This plugin adds another pane to the right of the gEdit window. After click the Right Side Pane from the View menu for the first time, the manage window would appear allows you to manage left and right pane allocation. After the first time, this window can be accessed through View -> Manage Left & Right Panes or press Ctrl+F10. This is useful for opening two panes at the same time like Eclipse and NetBeans editors.
  • Class Browser (http://www.stambouliote.de/projects/gedit_plugins.html)
    As the name suggests, this plugin lists the variables, functions, and classes for the current document to the Side Pane for easier navigation. However, it is not on-demand, meaning that the document needs to be saved in order to trigger the plugin to refresh to the latest version. It requires to install the ctags in order to use this plugin which is very easy. After the ctags was downloaded, just execute ./configure, make, and sudo make install to install ctags to the system. After that, restart gEdit in order to completely activate plugin.

Conclusion

These are some gEdit plugins which I think are useful to the developers. All of these plugins are from the official gEdit website (http://live.gnome.org/Gedit/Plugins). I believe that there are gEdit plugins out there other than this page. If you found additional plugins on other websites, please share them in the comments below.

Some Useful gEdit Plugins for Developers: Part Two – Third-Party Plugins (1)

Introduction

In part 1, I listed some useful development plugins in the default gEdit installation and the gedit-plugins. In this post, I will list the first batch of useful third-party plugins for developers from the third party gEdit plugins list (http://live.gnome.org/Gedit/Plugins).

The List

  • Advanced Find/Replace (http://code.google.com/p/advanced-find/)
    This plugin can search or replace specified characters whether in the current document, opened documents, or selected directory. The search results will be outputted to the Bottom Pane after a search is performed. It also highlights the search results in the document. It is useful to find a specified function or class within a project/directory.
  • AutoComplete (https://github.com/nagaozen/gedit-plugin-autocomplete/)
    This plugin suggests words that exists in the opened documents as you type. According to its website, I think it also suggests custom libraries although I was not tested it yet. It would save me lots of time to retype the function name.
  • Session Autosave (http://sourceforge.net/projects/geditautosaves/)
    Once this plugin is enabled, it will save the current opened tabs/documents on exit and reopen them when gEdit started next time. The feature is the exactly the same with NetBeans default feature for opening up last opened documents to continue editing them. However, I noticed that it only saves opened documents. This means that it will open the previously closed documents when gEdit started. The solution is to select Tools -> Session Save to refresh the session.

To Be Continued …

These are just a couple of plugins I tested. In the next post, I will list some more plugins useful for programming development. All the plugins mentioned in this post and the upcoming posts are available on the gEdit plugin page (http://live.gnome.org/Gedit/Plugins).

Do you have any gEdit plugins that does not list on the gEdit plugin page? Please share them in the comments below.

Some Useful gEdit Plugins for Developers: Part One – Default Plugins and gedit-plugins

Introduction

I recently found out that gEdit has some wonderful plugins that useful as an IDE and decided to search for the additional third-party plugins which work well for my development environment. This part is focused on the default installed plugins and gedit-plugins package (http://live.gnome.org/GeditPlugins) which is available in the repos of most distros. The next one (or two) part(s) will be focused on the third-party plugins (http://live.gnome.org/Gedit/Plugins).

The List

  • Code Comment
    This plugin is useful when commenting out part of the code for testing or other purpose. To comment or uncomment a block of code, select them and press Ctrl+M to comment and Shift+Ctrl+M to uncomment.
  • Color Picker
    This plugin is extremely useful to me because I always had issue with color assignment when using NetBeans and Bluefish since they don’t have an easy way to access color palette when writing CSS. To use the color picker, place the cursor where the color code will be placed, and then select Tools -> Pick Color to choose a color from the color palette.
  • Embedded Terminal
    This plugin shows an embedded terminal at the bottom panel. To see the bottom panel, select View -> Bottom Panel or press Ctrl+F9. This terminal is useful when writing a programming language such as C and want to compile and test the code without leaving the editor.
  • External Tools
    This plugin can be set up to work with external commands within the editor. It comes with some default commands and can be used as templates to add additional commands. To manage commands, select Tools -> Manage External Tools. The produced output would normally appear in the Shell Output tab at the Bottom Panel. However, it can be customized in the Manage External Tools window. If you don’t know how to write commands, here is the list of pre-made commands from the official gedit website (http://live.gnome.org/Gedit/ExternalToolsPluginCommands).
  • File Browser Pane
    This plugin adds a File Browser tab to the Side Panel. If the Side Panel is not open, select View->Side Panel or press F9 to open it. It could be useful when working on a project with multiple files or just browse through the folder and open the files without leaving the editor.
  • Snippets
    This plugin adds a menu item named Manage Snippets in the Tools menu. When creating a document and saved as specified format or change the highlight mode from the View menu, the snippets shortcut is activated for that format. When entered a shortcut and press Tab, the corresponding code defined in the snippets will be expanded and can be edited in the appropriate places. Press Tab again when finished editing to complete the statement.  Note that you can download additional snippets from the official gedit website (http://live.gnome.org/Gedit/SnippetsPluginsCodeSnippets).
  • Spell Checker
    This plugin adds spell checking feature similar to the spell checking in the Word Processor. After the plugin is enabled, the Autocheck spelling can be enabled from the Tools menu to check the spelling for the current documents automatically. A red line will appear below the incorrect word. Right-click the word and hover over the Spelling Suggestions to see the suggested words to be corrected.
  • Tag list
    Once this plugin is enabled, the tag list tab will be added to the Side Panel. It is useful for reference the appropriate tags and for adding the special characters which are hard to remember. The tag can be added to the current document by double-clicking the appropriate tag.

Build a Private Git Server using VirtualBox Bridged Network

I had been adjusting my new GNU/Linux environment with Arch Linux lately. Almost all the utilities that I need in Arch Linux were downloaded through the AUR and then compile and install them on demand which was pretty fast. Along with the software installation in Arch Linux, I also discovered Git version control system which I think it’s useful for version control  my website files. However, the only Git hosting provider GitHub offers 300MB of storage space which is not enough for my 600MB (and growing) website files. Therefore, I decided to build a private virtual Git server for self usage.

Virtual Git Server with VirtualBoxBackground

For a long time, I use NAT network interface as the default interface for the network when building a virtual machine with VirtualBox. Recently, I tried to build a virtual private Git server to version control my website files. I created a virtual machine in VirtualBox and customized it a little as usual, and installed Ubuntu Server as the server OS. After the installation was finished and logged into the server, I noticed that the IP address was 10.0.2.15 which can’t be accessed both by the host system and other systems on my home network. The Networking Modes section in the VirtualBox manual (http://www.virtualbox.org/manual/ch06.html#networkingmodes) explains that the NAT uses a virtual router to obtain the IP address whereas the Bridged uses a virtual network adapter to obtain the IP address which means that it obtained the IP address from my home router. This solves my problem for getting IP address for the virtual server to join my home network.

Steps

  1. Open VirtualBox.
  2. Choose the virtual machine with the network interface to be configured.
  3. Click Settings and select Network on the left.
  4. Choose Bridged Adapter in the “Attached to” list.
  5. Choose the appropriate physical network adapter in the Name list (I chose wlan0 since I’m using a netbook).
  6. Click OK to close the Settings dialog and click Start to start the virtual server.
  7. After the server was fully started and logged in, type “ifconfig” (without quote) to verify the IP address. If it’s like the format “192.168.0.x” or the format similar to your home network, the bridged networking is activated. Otherwise, visit the community forums (http://forums.virtualbox.org/) for help.
  8. Test the network – First, test on the host system: Type the IP address you got from the previous step into the browser on the host system (in my case, on the netbook). The network is working if “It works!” default web server page appears in the browser.
  9. Then, test on another system in the same network (which is my laptop): the same procedures as in the last step.
  10. If all went well, you should ssh from another system to the virtual server for remote access in order to create a Git repository.
  11. For more information on how to create a private Git server, read this article (http://tumblr.intranation.com/post/766290565/how-set-up-your-own-private-git-server-linux). The steps are the same except you are setting up in a virtual server instead of a real server.

Feel free to comment below if you have any questions regarding creating a server in the VirtualBox.

My First Static WordPress Plugin

After almost 3 hours of researches and trials, I finally finished the first one-page WordPress plugin called “identi.ca reminder”. As the name suggests, it’s used for reminding me to post an update whenever I added or updated a blog post. Since identi.ca (http://identi.ca/) also posts updates automatically to Twitter and Facebook, I only need to update the status for my identi.ca account. And because the lack of the good identi.ca-related WordPress plugins, I decided to manually update the status once a blog post is added or updated.

This was the first time I began to learn WordPress plugin. Thanks to the detailed documentation on the WordPress Codex wiki, I was able to learn and create the plugin at the same time. Here is the whole source code for my basic plugin (also includes very detailed comments):

<?php
/*
Plugin Name: identi.ca Reminder
Plugin URI: http://wordpress.org/#
Description: This is my first plugin simply remind you to post an update on identi.ca after a blog post is published/updated
Author: Robby Chen
Version: 1
Author URI: http://blog.robbychen.com/
*/

    // Function to output the reminder
function reminderID($messages) {
    $reminder = array();    // An empty array to store the duplication of the messages array
    $others = array();      // An empty array to store the arrays for post types other than messages['post']
    foreach ($messages['post'] as $num=>$message) {
        $message .= "<br /><br />Make sure to update your <a href='http://www.identi.ca/robbychen' target='_blank'>identi.ca</a> status.";
        if ($num == 0) {
            $message = "";  // The first element in the messages['post'] array is always empty
        }
        array_push($reminder, $message);    // Insert/copy the modified message value to the last element of reminder array
    }
    $reminder = array("post"=>$reminder);   // Apply the post key to the first dimension of messages array
    foreach ($messages as $type=>$message) {
        if ($type == "post") {  // Skip the post key since it is already defined
            continue;
        }
        $others[$type] = $message; // Since message is an array, this statement forms 2D array
    }
    $reminder = array_merge($reminder, $others);    // Merge the arrays in the others array with reminder array in order to form an appropriate format for messages array
    return $reminder;
}
    // Print the above message when a blog post is submitted or updated
add_filter("post_updated_messages", "reminderID");
?>

Note that when I wrote and tested this plugin, the “messages[‘post’]” array cannot be changed partially. The only way I can change the value is to copy the modified value to a new array, then make the structure of the new array the same as messages’. For instance, I tried to do the following in the code above:

$messages = array('post'=>array(), 'page'=>array(), 'custom_types'=>array(), ...);
$reminder = array('post'=>array(), 'page'=>array(), 'custom_types'=>array(), ...);

It seems that without this format, the add_filter function would not be executed. As the above example shows, it just applies to the “post” post type, although I have not tested it with custom post type yet.

You can download the source file here.

Below are the resources I used to help me for creating this plugin: