Sunday, December 17, 2006

Your own uname!

Adding another simple code to find some basic system information on Linux/Unix machines.
There are some API's, you will need to do some input parsing, which you can add to make this act as your own "uname" command!!

I have not added those to keep the code clean and simple....KISS - "Keep It Simple Stupid"



#include "sys/utsname.h"
#include "iostream"
#include "stdlib.h"

int main()
{
struct utsname name; // Structure to hold the system info.

if(uname(&name)==-1){
perror("System error:: ");
return -1;
}
cout << "sysname == " << name.sysname <<
" release == " << name.release <<
" version == " << name.version <<
" machine == " << name.machine <<
endl;
return 0;
}

NOTE : The above code compiles under Linux/Unix for sure. Have not tested on other platforms...


Here are the functions I wrote for parsing the input string....You can use them if you want
CALLING PI is : parse_argv(argc, argv, name); // You will have to add this in main after the if{}

template < class T>
void
printErr(T str_ch)
{
cout << "Invalid option..." << str_ch <<
"\tUsage: uname [-m][-r][-v][-s]" << endl;
}

void
parse_argv(int argc, char** argv, const utsname& sysinfo)
{
while(--argc) { // Check arguments supplied or not as argc == 1 imp no args
char* str = *(argv+ argc);
if('-' == *str ) { // - imp option specifed or not
while( *++str ) {
switch( *str )
{
case 's': cout << " System == " << sysinfo.sysname << endl; break;
case 'm': cout << " Machine == " << sysinfo.machine << endl; break;
case 'v': cout << " Version == " << sysinfo.version << endl; break;
case 'r': cout << " Release == " << sysinfo.release << endl; break;
default : printErr(*str);
}
}
} else {
printErr(*(argv + argc));
}
}
}

Tuesday, December 12, 2006

Fun with programming

Well another interesting piece of code I came across on some website....sorry I forgot the source. But I claim no responsibility or originality of the code....

It is called a quine....
Well quine is a piece of code that outputs itself exaclty.
Search on the net and you will find many more of thses examples. Search for "quine"

Here is the one i liked!
main(){char *c="main(){char *c=%c%s%c;printf(c,34,c,34);}";printf(c,34,c,34);}

Just compile and run the code....and enjoy the beauty of "C programming"

****************************************************************************

Here is another of my favourite fun code in C....
Program without the omni present main()....

// Code to print hello without main()
// compile gcc -nostartfiles filename.c

#include "stdlib.h"
#include "stdio.h"
_start()
{
printf("Hello World\n");
exit(0); // If no exit seg fault "Cannot find bounds of current function"
}

That is all folks...
I might update the page if i find some new interesting things...till then
Happy Coding :)

Monday, December 11, 2006

Remove those spaces!!

Its been a long time since I have posted something new and useful...well have been really busy with life!!

Here is a code I wrote for fun...it removes all the multiple tabs and blank spaces in a string.

Feel free to use it, but do give credit to the Author :)
And if you find any issues...or feel like giving some feed back...you are most welcome!!



/*
* Date: 10th December 2006
* Simple Utility code written by hundredrabh
* It simply removes more than 4 spaces and tab stops
* from the input string and replaces them with space.
* You can download and play with the code
* But please do give due credit to the author for his efforts!!
* Happy Coding
*/

#include "stdio.h"
#include "stdlib.h"

/* Function declaration and defination */

/* char* enterString(char*)
* Accepts a char pointer, to return the input string
* returns a pointer to the input string, and this pointer needs to be freed by the user!
* Error checking needs to be added for return values and realloc
// TODO - Enhance it for buffered reading/writing
// As realloc is slow....
*/
char*
enterString(char* str)
{
char ch;
int len = 0;
while(10 != (ch = fgetc(stdin)))
{
if(0 == (len % 512)) {
str = (char*)realloc(str, len + 513); // TODO - Need Error Checking here...
}
*(str + len) = ch;
*(str + len + 1) = '\0'; // adding the null termination as realloc does not return 0ed memory..so EOS determination is difficult.
++len;
}
return str; // This needs to be freed by the user
}

/* End of enterString(char*) */

/* DETAB
* void detab(const char*)
* returns a void, accepts a char*
* remove all the tab spaces or spaces which are in multiples of 4 from the string
* Spaces before and after a tab will be considered as continuous!!
*
*/
void
detab(char* str)
{
char* dummyRetStr = str;
int spaces = 0;
while(*str)
{
switch(*str)
{
case '\t': // Remove the tab
*str = ' ';
++spaces;
break;
// check for 4 spaces together
case ' ' :
++spaces;
break;
default :
spaces = 0;
break;
}
*dummyRetStr++ = *str++;
if(spaces == 4) dummyRetStr -=3, spaces =1; // Remove 4 spaces occuring together!
}
*dummyRetStr = '\0'; // null terminate the modified string
}


int
main()
{
char *inp = 0;
printf("Enter the string \n");

inp = enterString(inp); // Free inp, it has been malloced
detab(inp);

printf("You entered .... %s\n", inp);
realloc(inp, 0);
return 0;
}

Thursday, June 15, 2006

Bug of the week - 15 june 2006

Well this blog will be a bit techie one!!

There was a certain problem I faced while compiling a small cpp test code.
Whacked my brains for 3hrs to find this small bug!!
maybe a pro would have found it earlier!!

but here goes the problem!!


1 #include < iostream>
2
3 using namespace std;
4
5 class A {
6 public:
7 A( int a ): x( a ) {}
8 int getX() const { return x; }
9 void setX( int a ) { x = a; }
10 virtual void abc( void );
11 virtual ~A() {}
12 protected:
13 int x;
14 };
15
16 class B : public A {
17 public:
18 B( int a ) : A( a ) {}
19 void abc ( void ) { cout << "its B" << endl; }
20 ~B() { cout << "ending B" << endl; }
21 };
22
23 class C : public A {
24 public:
25 C( int a ) : A( a ) {}
26 void abc ( void ) { cout << "its C" << endl; }
27 ~C() { cout << "ending C" << endl; }
28 };
29
30 int main() {
31 B b = B( 1 );
32 C c = C( 2 );
33 cout << "b is : " << b.getX() << " C: " << c.getX() << endl;
34 b.abc();
35 c.abc();
36 return 0;
37 }

Now when compiled with g++ the code gives the following lonker error!!
/tmp/ccQfBUdf.o(.gnu.linkonce.t._ZN1AD2Ev+0xb): In function `A::~A()':
: undefined reference to `vtable for A'
/tmp/ccQfBUdf.o(.gnu.linkonce.t._ZN1AC2Ei+0x8): In function `A::A(int)':
: undefined reference to `vtable for A'
/tmp/ccQfBUdf.o(.gnu.linkonce.r._ZTI1B+0x8): undefined reference to `typeinfo for A'
/tmp/ccQfBUdf.o(.gnu.linkonce.r._ZTI1C+0x8): undefined reference to `typeinfo for A'
collect2: ld returned 1 exit status


Now for the bug!!

Well it was a small issue...
You ought to give a dummy implementation of virtual function abc at line 10 as



10 virtual void abc( void ){} or
10 virtual void abc( void ) = 0; make it a pure virtual function...

it will compile as a charm!!

Happy coding!!

Friday, May 26, 2006

Social Justice .. Other Means

This blog is to express my views against the 50% reservation policy of the Indian Goverment..

Why do our leaders think that making reservations in higher education will bring social equality in India? I beg of them not to do such grave injustice to the common people of India and contemplate over some other alternatives.

All the measures should be implemented at the grass-root level. So that all a poor/backward student needs at the higher level is scholarships and financial aid, which of course can be provided. But introducing reservation in higher education will not be an effective measure. You cannot teach a person integral if he is not comfortable with addition.

Instead of the mid-day meals, why not give the students money itself(I may not be fully correct here). It will be an added incentive for their poor parents to send their wards to school. You can introduce 2 mandatory credits in MBBS, BTech, MBA, BCom, etc for a person to teach in rural areas. Village panchayats should look after the boarding and lodging of these people and government should pay them minimla wages. This will resolve teacher shortage crisis and also help people connect with the grass root level. This way people will also take their modern outlook and ideas to the village, resulting in upliftment of the village as a whole. Other countries have 5 years of mandatory army duty. We can have atleast 6 months of teaching job?

This reservation policy will only further divide the nation which will be orthogonal to the vision of equality which our freedom fighters died for. We should look for progressive policies not these regressive ones. This might win them more votes in the next election or so..but as an Indian why dont they think what harm it will do as a whole to the country. Sometimes a person needs to rise above the petty political games. But maybe these people have sold their soul in order to achieve their personal greed.
Writing with a lot of hope and faith!! Hum honge kamyaab......
Inqulab Zindabaad!!

Wednesday, March 01, 2006

The Invisibles!!

The other day while whiling my time at Chennai Mofussil Bus Terminus(CMBT,India) at 4:00a.m in the morning(Don't ask what I was doing there at such a weird time). I had the opportunity to observe the otherwise not so visible bi-peds. Those who have a great bearing on how smoothly our lives function, yet unknown to us. I am talking about the daily wage worker, the rickshaw wala et-al.
They all seemed to be sleeping on the dirty floor with some old newspapers neatly and appropriately placed below them as though these were their "prized" bed-covers. Most of them seemed like sleeping in a state of trance, dreaming for what they really dream!! Far away in their own sweet world.

Then from somewhere comes the deafening noise as though there is a cloud burst.
It was the policeman who had come to wake them to the realities of life.
The sound of the policeman's "Lathi" hitting the ground made most of them sit upright and look as though they were awake...But their half sleepy eyes gave away the truth.

Most of them sat up, to move on and face another day in their lives which somehow was not comfortable for them. while some of them slept nonchalantly knowing it was a daily routine. They sat up and went back to those sweet dreams, as though not wanting to face the "realities", as soon as the policeman left. Those who had woken had by this time disappeared in the crowd as "the invisibles" ready to support the human civilization hoping for once they get their due credit.

Watching all this made me realize how indifferent we are to our fellow beings and how we "overlook" the implied. Anyhow it was time for me to move on and try to figure out how not to ignore "the invisibles" from now on........

Can see them really!!!

Friday, December 30, 2005

Happy New Year!!

Happy New Year
As the sun sets for 2005,
Another great chapter closes in our lives.
We usher into a new era in 2006,
hoping not to be haunted by for what we've already given a fix!

Yesteryear was a great one,
full of enjoyment n loads of fun.
I hope that 2006 is equally prosperous and bright,
with you achieving, on whatever you set ur sight.

Raise the "BAR" and ensure all hurdles are crossed,
and you do not take the path that is already falsed.
So, Another great year comes to an end,
time to say "HAPPY NEW YEAR" to all,
near-dear and good friends!!

Happy New Year to all!!!

Tuesday, December 20, 2005

Questions unanswered.....

Not once, not twice, neither thrice. I ask myself infinite times.

Why all this? For whom? What is the purpose of this life?
I came, I saw, I tried to make the best for myself. Because its me who is affected.
That sounds a lot of "me", "myself" and "I" to me!!
Why cant it be more "we","us", "them"?
Is this this "I" the sole purpose of our existence or is it "us" ?

It feels somewhere down the line we loose the meaning , the sole essence of life.
If we try to cut out that "I" and "me" replace it with "us" and "we".I think this world can be a better place.
After all we know how to respect other peoples emotions and feelings. That can come out in a better way if we respect "them". I have tried it many a times and have never faced failure, but don't know how to make it a more universal feeling/phenomena.

Maybe I think the wrong way...may be I miss the point somewhere...but still i feel that this is not the way it should be. I try to figure out what is amiss...
But alas in the end find my "questions unanswered"!!

Monday, November 14, 2005

A Journey in Indian Railways.....

This weekend I had the "once in a lifetime opportunity" to travel in a general compartment of Indian Railways. The experience was a little short of a nightmare that you dream should never come true.

I will mention some of the inumerable instances that made the journey really tiring and discomforting.

First hurdle was buying tickets. To start with I was lucky enough not to stand in the long unwinding queue to buy the tickets. One of my friends bought the tickets and in all the jostling lost a Rs.500 note,but to look at the brighter side he came out of the queue unharmed and more pleasantly with 4 tickets for us. (First battle for tickets won!!).

Then came the challenge to get a seat, as 4 hour long journey can be really taxing on your un-exercised legs. There was a sea of people wanting to jump into the bogey. I could not imagine so many people fitting into that small compartment but I could figure out this reason later when I learnt that it was a norm for 4 ,even 5 people sometimes, to sit on a seat marked with 3 distinct integers. My assumption that 3 numbers meant that 3 people could sit on it was wrong.
Again one of my friends who was well accustomed to all this had a small trick up his sleeve. He jumped,as everyone else did, into one of the compartments while the train was coming to a stop at the station. And hence we managed to get 2 seats for 4 of us to sit.The alley between the seats was supposed to have zero voids with all available space to be used by the traveling "junta" to stand and travel("suffer").

Traveling from then on was a little more comfortable. With only the person next to you pushing you more and more to sit more comfortably,you literally had to fight for survival.But somehow after a few pushes and nudges everyone was settled and able to adjust. Now if you are lucky/unlucky to have a window seat you can have the full view of a**es of people trying to answer mother natures' call, early morning. All the stinking sweat; yours and of the people around you is something you should be prepared to bear with. After all we are a tolerant society! Somehow we pass our time playing cards or listening to music from my newest gizmo, a Samsung digital music player, we reach your destination. After realizing that you have passed this endurance test you, notice that your face and hair all having a fine coating of dust which due to mixing with sweat forms into a thin crust. But the realization of having successfully traveled in such adverse conditions, you are happy. And all the sweat and mud is just a symbol of labour and effort you have put in. But that faint smile on your face disappears soon as you realize that you have to return the same day. Thoughts of going again through that ordeal makes you sweat already and drain whatever water your body has been able to retain.

Wednesday, September 14, 2005

Where Why When ???

Where are those happy days?

Why don't we feel the fresh air .... see the rising sun.. hear the chirping birds and sip the morning dew.
Now the air is already conditioned .... halogens have replaced those golden sunrays ..... birds are all gone,not south but somewhere i surely can't hear and the dew drops are slowly converting into tears which i myself drink,quietly.
Why can't i fly like the falcon high in the sky?

When can i give wings to my dreams so that they can soar high? They no longer be a dream but a reality which will bring joy to the morose soul.

But a ray of hope is still there ... you can see the rays if you switch off those halogens that blind you.
switch off the conditioner and open those closed doors and windows ... move out of the closet ,come out in open .. hear those birds and feel the fresh dew. This flickering ray will become more radiant when we hear what our ailing heart cries for and follow the message. The message it wants to put across........

Then only this quandry , predicament will subside and we will relish the true ecstacy in life!!!!!

Sunday, August 21, 2005

All Lost.............

This is how it feels to leave the college and enter the corporate world!!! How it feels when those starry dreams ain't fulfilled.When you miss all your friends.Who too are consumed by this corporate world leaving little time for ol' pals to sit back, meet and relax.
No more chats, news n reviews....
Life it seems is drifting too fast or is it just inertia?
Lethargy is now not just a feeling its a habit.

The corporate world has drained all the energy from the spirited soul.
The zeal is no longer there and the fire within has extinguished.......
But still we come daily , do the cursed job ,do not crib
though this heart bleeds within......
Is this what the dreams were all about??
or was it just a fallacy, a mirage???