Friday, June 25, 2010

Some weird stuff about Ant

Currently I was using Ant with TestNG, please take note that when taskdef was missing in the code, the error is misleading.

<taskdef name="testng" classpathref="compilePath" classname="org.testng.TestNGAntTask" />

Below are the error generated:

Cause: The name is undefined.

Action: Check the spelling.

Action: Check that any custom tasks/types have been declared.

Action: Check that any <presetdef>/<macrodef> declarations have taken place.

Sunday, June 13, 2010

std::nothrow new

Sometime during the new operation it might fail the process due to certain reason, this isn’t a big deal because exception could be a good friend to help out. Unfortunately exception still have its own limitation where it might not able to find the matching catch() clause due to the mistake of programmer. Or it could be in other situation; CRT’s new will return a NULL pointer whereas standard C++ will throw a std::bad_alloc exception when memory allocation failed.

Instead of worrying:-
1. How does the programmer know about how the exception going to catch?
2. The programmer has to be aware that he/she is dealing with CRT’s version of new or standard version of new.

Let’s put in alternative point of view:
What if the programmer knows that the new operator is NOT going to throwing any exceptions?

Thus, std::nothrow new would be the best solution. This will guarantee that the new will only return either a NULL pointer or a valid pointer.

Here is the sample usage:
Foo *p;
p = new(std::nothrow) Foo();
if( !p ) { exit(1); }

reference
1. msdn reference
2. C++ reference guide

Saturday, June 12, 2010

How to get a file size?

stat structure is the guy to retrieve the file information, and this structure has a field called st_size where this field will retrieve the file size in bytes.

Here is the sample code:

struct stat FileStat;
if( stat( "MyFile", &FileStat ) == 0 ) { cout << FileStat.st_size << endl; }

Who is popen()?

I found a new function called popen() in stdio.h. This is so interesting that this function wasn't in the C Programming Language (ANSI) but can be found in the Standard C Library book, according to this page. This function is useful where it can direct the *NIX (e.g. ls -l) command into a FILE pointer, and read the desire output from that pointer.

For example, ls -l command was type in the console like this:
huahsin68@huahsin68-laptop:~/Development/TestLab$ ls -l
total 12
drwxr-xr-x 3 huahsin68 huahsin68 4096 2010-06-12 19:45 Debug
-rw-r--r-- 1 huahsin68 huahsin68 241 2010-03-27 15:00 MyLog.000.txt
drwxr-xr-x 4 huahsin68 huahsin68 4096 2010-03-27 12:19 src
the same thing can be done using popen(), each line of the output will be direct to FILE pointer. Use fgets() to retrieve each line of the output. Below is the sample code:
FILE *fp;
char line[130];

fp = popen("ls -l", "r");
while ( fgets( line, sizeof line, fp)) {
   printf("%s", line);
}
pclose(fp);