Tag Archive for 'function'

A Logger In C

Now I am working on this fair scheduling for my B Tech Project (BTP). Already having written a 1000 lines of code, it is a great pain to debug it. More so if you do not know which function might have caused the error. I needed a logger which could log all the events. The events include entering a function, any important calculation/decision it makes, any return values, so that if my program breaks down I can exactly pinpoint the source of error simply looking at the log file generated.

I have no idea if any inbuilt logging functionality exists for C programs or not. Either way, I did not have much time to google up and learn how to use it. I decided to make my own logger, a simple one, which would serve my purpose. It hardly took me 10 minutes to get over with it.

One of the important functionalities that I wanted my logger to have is indentation. The log should be properly indented, just the same way as we indent the code. When the program control enters a new function, the logging should get indented to right, and when it leaves the function, the logging should get indented by the same amount to the left. So I defined two macros, INDENT and OUTDENT. To make them work, I defined a global variable – logIndent. The logIndent would at any given time contain the amount of space by which the log has to be indented. Obviously, I initialized it with 0. Also defined is a global variable called indentVal which is the amount of spaces with which the indentation should take place. I like the value to be 2. The two macros are

#define INDENT logIndent += indentVal
#define OUTDENT logIndent -= indentVal

int indentVal = 2;
int logIndent = 0;

I defined another macro called SPACES which would print the number of spaces to produce the required indentation.

int tempIndent;
FILE *logFile;
#define SPACES for(tempIndent = 0; tempIndent < logIndent; tempIndent++) fprintf(logFile, " ");

Obviously tempIndent is a globally declared temporary variable and logFile is the file pointer to the file where the log has to be written. I initialize the logFile pointer in the main() part of my program.

And finally coming to the logger, I created a custom printf() statement using the vprintf() command. I call my logger as LogThis(). Its declaration is as follows

void LogThis(const char *format, ...);

It is constructed as follows

void LogThis(const char *format, ...) {
  va_list args;
  va_start(args, format);
  SPACES;
  vfprintf(logFile, format, args);
  va_end(args);
}

That’s it ! To use this logger, I have to do the following in my function :

#include <stdio.h>
#include <stdarg.h>
void TestLogger() {
  int returnVal;
  float retVal;

  LogThis("<TestLogger>\n");
  INDENT;

  /**
   *  Inside the function do whatever you want to
   */

  LogThis("Returns: %d, %f\n", retrunVal, retVal)

  OUTDENT;
  LogThis("</TestLogger>\n");
}

Done ! A well indented log will be produced. This has really helped me debug the code. I do not have to gdb from the last point that worked in my program. Instead, I know which function the program control was in when it threw an error. I need to gdb from that function onwards only, thus reducing the debuging time considerably. Also, in case of errors, I can increase the debugging data for that particular function, thus eliminating the need to use gdb at all.

php – Sessions

After a long long time I was back to coding in php. And by long time, I mean atleast 24 months ! Believe me, it wasn’t easy. More so because of the higher standard I have set for myself. My code this time shall be much neater and easier to read than it ever was.

The past four years of my life has been spent coding. And when you code so long, you modify your habits to get tuned to the proper way of coding. As it is said, a person spends more time reading a code than writing it. So this time I am taking special care of writing simpler and smaller functions so as to make the code more readable. Also, since I have been reading a lot of OOP these days, I am intent on providing an abstraction layer for the user, so that at the top most level coding should appear like writing a few english sentences rather than some cryptic mysqli_select_db things.

This is the first time I am trying to code in php following the OOP structure. Also, though this might seem strange, it is the first time I am using session variables in my design! Below is a trivia I had not known earlier, and spent 2 hours trying to understand what was wrong in my seemingly proper and correct code.

A session created with session_start will only be available to pages within the directory tree of the page that first created it.

i.e. If the page that first creates the session is /dir1/dir2/index.php and the user then goes to any page above dir2 (e.g. /dir1/index.php), session_start will create a new session rather than use the existing one.

Also I found the following class to be useful.

<?php
class Session {
public <a class="zem_slink" title="Method (computer science)" rel="wikipedia" href="http://en.wikipedia.org/wiki/Method_%28computer_science%29">static function</a> Init() {
self::Commence();
}

public static function Set($fld, $val) {
self::Commence();
$_SESSION[$fld] = $val;
}

public static function un_set($fld) {
self::Commence();
unset($_SESSION[$fld]);
}

public static function Destroy() {
self::Commence();
unset($_SESSION);
session_destroy();
}

public static function Get($fld) {
self::Commence();
return $_SESSION[$fld];
}

public static function is_set($fld) {
self::Commence();
return isset($_SESSION[$fld]);
}

private function Commence() {
if(!isset($_SESSION['ready'])) {
session_start();
$_SESSION['ready'] = TRUE;
}
}
}
?>
Reblog this post [with Zemanta]

php5 OOP – Function Overloading

PHP

PHP

Starting php4, object oriented concepts have been made available to the programmer. Though not well developed, they paved the way for a more complete implementation of the OOP basics in the php5 version. However, one thing that remains lacking is the ability ot overload the functions.

Overloading of functions is quite an useful feature. In the simplest form, it gives you the freedom to declare a class with more than one constructors.

Not to get disheartened though, we have a simple enough way to work around this short coming. In php, when a call is made to a function that does not exist, then the control searches for the __call() function. We make use of this to carve out the over loading feature that we need.

Below, I am writing the code for a Register class which has two variables – name and pass. The constructor is being overloaded here.

class Register {
private $name;
private $pass;

public function Register() {
$num = func_num_args();
$args = func_get_args();

$funcName = 'Register'.$num;
$this->__call($funcName, $args);
}

private function Register0() {
$this->name = '';
$this->pass = '';
}

private function Register2($name, $pass) {
$this->name = $name;
$this->pass = $pass;
}

public function __call($funcName, $args) {
$this->call_user_func_array(array($this, $funcName), $args);
}

public function setName($name) {
$this->name = $name;
}

public function setPass($pass) {
$this->pass = $pass;
}
} // Register

// regA is using the Register2() constructor
$regA = new Register('Anu', '@#$#@$@$');

// regB is using the Register0() contructor
// and subsequently setting the values of name, pass
$regB = new Register();
$regB->setName('Anu');
$regB->setPass('@#$#@$@$');
Reblog this post [with Zemanta]

Variadic Functions

C is a beautiful language. Though I have been using it for a few years now, I have yet completely mastered it. Just now, I stumbled across what are called variadic functions.

Have you ever wondered how to write functions that take in variable numbers or arguments? Take for instance printf() or scanf(). Both have been implemented in C. These are called variadic functions.

Problem: To construct a function which can take variable number of inputs, eg; printf()

Solution:

Its a simple matter of using built in macros defined in the stdarg.h library. It provides the following macros:

  • va_list: The list of argument
  • va_start: Initializes va_list to the first unnamed argument
  • va_arg: Takes the current variable and the type
  • va_end: Called at the end

Through a self explaining example I would like to demonstrate the usage of these macros. Let us define a new function called PBAPrint() which imitates the printf() function.  For example,

PBAPrint(”df”, 12, 2.2) outputs: int = 12 float = 2.2

PBAPrint is implemented as follows:


void PBAPrint(char *format, ...) {
  va_list ap;

  va_start(ap, format);

  while(*format) {
    if(*format == 'd')
      printf("int = %d ", va_arg(ap, int));
    else if(*format == 'f')
      printf("float = %f ", va_arg(ap, float));
    else {
      printf("unsupported format ");
      break;
    }
    format++;
  }

  va_end(ap);

  return;
}

But apparently things are much more simpler when using C++.




Theme Tweaker by Unreal