Wednesday, October 30, 2013

Qt conversion from date to qstring and from qstring to date


Qt provides very nice library to handle Date and Time. We can use them and convert from Date and Time to Qstring and vice-versa. Below is the sample code snippets providing for both conversion from date to string and string to date in Qt.

Conversion from QDateTime to QString: Below is the sample code for converting datetime to string in Qt. Qt has many string formats to retrieve day, month, year in different formats. for more info check here.

QString dateToString(QDateTime d)
{
    //these three statements just for info.
    QString day = d.toString("dd");
    QString month = d.toString("MM");
    QString year = d.toString("yyyy");

    return d.toString("dd")+"/"+d.toString("MM")+"/"+d.toString("yyyy");
}


Conversion from QString to QDateTime: Below is the sample code to convert from string to date and if the date format string is "dd/mm/yyyy". if the format is different, you need to add corresponding order to get the proper date as the code first converts the string to list using convertQDatetoList  and from list to date as below.

QVariantList convertQDatetoList(QString dateTime)
{
    QStringList tempList = dateTime.split("/");
    QVariantList dateList;
    QListIterator i(tempList);
    while(i.hasNext()) {
     dateList.append(i.next());
    }
    return dateList;
}

QDateTime setDateFromString(QString dateString)
{
 QDateTime dt;
    QVariantList dateAsList = convertQDatetoList(dateString);
    if(dateAsList.size()==3) {
     QDate t(dateAsList.at(2).toInt(),
                dateAsList.at(1).toInt(),
                dateAsList.at(0).toInt());
     dt.setDate(t);
    }
    else {
     //date format is not valid,so setting the current date
     dt = QDateTime::currentDateTime();
    }
 return dt;
}


Thursday, October 24, 2013

What is strdup string function in C Language?

strdup string library function is used to create the duplicate string. It will do the following three steps.

  • It creates the dynamic memory (no need to use malloc/calloc)
  • It copies the content to the newly allocated memory 
  • It returns the allocated memory starting address
When we are using strdup function, we need use the free() function do deallocate memory which is allocated by strdup function, other we will get into the memory leak. Check the below sample code.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define ONE_INT 1
void display()
{
     int local_a = 7;
     int *local_p = (int *)malloc(ONE_INT);
     printf("local memory location is %p\n",&local_a);
     printf("memory location using malloc is %p\n",local_p);
}
int main()
{
   char str_a[] = "Hello World";
   char *str_p = strdup(str_a);
   printf("local meory location is %p\n",str_a);
   printf("strdup memory location is %p\n",str_p);
   display();
}
OutPut:
local meory location is 0x7fff54cc0ba8
strdup memory location is 0x7fd0904000e0
local memory location is 0x7fff54cc0b7c
memory location using malloc is 0x7fd0904038a0

We can clearly observe that red colour address is from heap and blue colour address is from Stack. 

Sunday, October 20, 2013

ant build file isset property not working

One of the common mistake when checking the property value in the ant build file is putting $ in the condition check in the isset flag. for isset , just specifying the property name is fine, and $ is not required. If $ specify, it will take the property value and checks property value as a property or not. below is the sample ant build file code .


Defining a new property in Ant build file: property, name and value are key words. Syntax is given below. there is no data type for the property. we can give any value like, string, numeric or directory path, file path etc.

<!-- defining a new property -->
<property name="test" value="this is variable"/>

Accessing a property value Ant build file:  We can access property value by using $.  Prepend $ for the property name and use in the echo, condition check etc. Below is the property value access in echo.

<!-- accessing a property value -->
<echo message="test value is $test"/>


correct way of using isset: $ is not required in the condition check
<if>
  <isset property="test"/>
  <then>
     <!-- success and test is a property-->
  </then>
</if>

wrong way of using isset: Putting $ is a wrong way
<if>
  <isset property="$test"/>
  <then>
    <!-- it wont come here, because $test is not a property-->
  </then>
</if>


Thursday, October 17, 2013

What is the difference between exit() and _exit() in C and Unix

In C programming language, exit function is used to terminate the process. Exit function will be called automatically when the program is terminates. exit() cleans up the user-mode data related to library. exit() function internally calls _exit() function which cleans up kernel related data before terminating the process.

    exit() flushes the IO related buffer before exiting the process and calls the _exit() function. Where as _exit() function just terminates the process without cleaning up or flushing user data. It is not advisable to call the _exit() function in your programming until unless you are very clear. There is another function called _Exit() function which also works same as _exit() functionally. We need to use strlid.h for exit() and unistd.h for _exit() functions.

Sample code with exit function:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
        printf("Hello");
        exit(0);
}
Output:
programs$ ./a.out
Helloprograms$


Explanation: 
Result we got  as expected and there is no \n at the end, so on the same line prompt came.

Sample code with _exit function:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
        printf("Hello");
        _exit(0);
}
OutPut: 
It prints nothing. 
Explanation:
This is due to ,we called _exit() function directly, so IO related data is not flushed, so printf data is not flushed, because of this, it has printed nothing.

Sample code with _exit function with \n:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
        printf("Hello\n");
        _exit(0);
}
OutPut:
programs$ ./a.out
Hello
programs$

Explanation:
We got the output Hello,  this is due to we are forcefully flushing the data using '\n'. Infact printf() function wont print or flush the data until buffer completes or end of the character is \n. printf internally maintains some buffer.

Using GDB, we can see functions which are called when the process terminates.  giving below for your info for simple c program
int main()
{
  printf("Hello");
}

programs$ gdb a.out
GNU gdb 6.3.50-20050815 (Apple version gdb-1824) (Wed Feb  6 22:51:23 UTC 2013)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin"...Reading symbols for shared libraries .. done

(gdb) br main
Breakpoint 1 at 0x100000f14: file _exit.c, line 5.
(gdb) r
Starting program: /Users/kh1279/Desktop/practice/Blog/programs/a.out 
Reading symbols for shared libraries +............................. done

Breakpoint 1, main () at _exit.c:5
5		printf("Hello");
(gdb) 
(gdb) n
6	}
(gdb) 
0x00007fff933ab7e1 in start ()
(gdb) 
Single stepping until exit from function start, 
which has no line number information.
0x00007fff933ab808 in dyld_stub_exit ()
(gdb) 
Single stepping until exit from function dyld_stub_exit, 
which has no line number information.
0x00007fff8b4a4f74 in exit ()
(gdb) 
Single stepping until exit from function exit, 
which has no line number information.
Hello0x00007fff8b4eb576 in dyld_stub___exit ()
(gdb) 
Single stepping until exit from function dyld_stub___exit, 
which has no line number information.
0x00007fff8efa3ae0 in _exit ()
(gdb) 
Single stepping until exit from function _exit, 
which has no line number information.

Program exited with code 0377.
(gdb) 
The program is not being run.
(gdb) 

Explanation:
 you just compile your program using -g  option for gcc,  without this option, we cant use GDB. after compilation, launch GDB debugger using gdb with a.out or your program binary file. put a break point at main function and forward using next or n gdb command. You can find the exit and _exit functions calling in the above gdb process in red colour.

Sunday, October 13, 2013

What is the return type of the printf() function in C


printf  function return type is integer. As most of us knows that, printf function is used to print content in the specified format on the standard output. It returns the no.of characters it printed on the standard out put device. i.e for hello string, printf function returns 5 as length of the string is 5 and for integer value 200, printf returns 3  as 200 contains three characters. and for float value 20.034 it returns 6 as it has 6 characters including dot. printf treats \n as a character, so if you use \n in the printf function, return value includes \n as well. sample code and syntax , see below.

Syntax for printf function in C:


int printf(const char * restrict format, ...)


Example with characters:

#include<stdio.h>
int main()
{
    int i = printf("string is %s","hello");
    int j = printf("\n%s","hello");
    printf("\ni value is %d\n",i);
    printf("j value is %d\n",j);
}

OutPut: 

string is hello
hello
i value is 15
j value is 6


Example with Integers:
#include<stdio.h>
int main()
{
    int j=200;
    int k=20;
    int i = printf("%d",j);
    int l = printf("\n%d",k);
    printf("\ni value is %d\n",i);
    printf("l value is %d\n",l);
}
OutPut: 

200
20
i value is 3
l value is 3


Example with Float and character:

#include#include<stdio.h>
int main()
{
    float k=20.034;
    int c='a';
    int i = printf("%d",c);
    int a = printf("%c",c);
    int l = printf("\n%f",k);
    printf("\ni value is %d\n",i);
    printf("a value is %d\n",a);
    printf("l value is %d\n",l);
}

OutPut:

97a
20.034000
i value is 2
a value is 1
l value is 10

Saturday, October 5, 2013

What is the return value of the main() function in C?

As per standard C , main() function always returns int. mostly zero if it is success and error code if it fails. some compilers accepts void as a return type for main() function. But standard compilers like gcc will give you the warning at the time of compilation saying that void is not allowed as a return type for the main() function.

#include<stdio.h>
void main()
{
        printf("testing return type for main");
}

Below is the warning message you will get when compiling using GCC for the above sample code:

$ gcc main.c
main.c: In function ‘main’:
main.c:3: warning: return type of ‘main’ is not ‘int’


Why main() returns int: In C , main() is the  user entry point to execute the code, so whatever writing the code in main, it is user specified code. But internally C execute many functions before and after the main function to startup and exit the program/application.  So when exiting C program, it calls exit() function and it internally calls _exit() function to exit the program. This exit process, specifies whether exit process completed successfully or any failure occurred due to some reason. If success it returns zero and if it fails it will return error code which is generally a numeric value. so logically it should return integer.

Friday, October 4, 2013

How to call function before main() function in C

Calling a user defined function before main() function: This is possible using function attributes. The standard C supports attributes syntax which is compiler dependent. C also supports type attributes, variable attributes. For more details about attributes click here.

     Using function attributes, we can call the function before the main function by specifying the parameter as constructor. This will be called at startup and mostly when shared libraries are called. We can also use destructor for calling the method after main() function, which indicates the exit of the application/program.

Below is the sample code:

#include&lt;stdio.h>
void beforeMain() __attribute__((constructor));
void afterMain() __attribute__((destructor));

void beforeMain()
{
        printf("before main \n");
}

void afterMain()
{
        printf("after main \n");
}


int main()
{
        printf("In main function \n");
        printf("leaving main function \n");
}

Output: below is the result of the above program.

$ ./a.out
before main
In main function
leaving main function
after main

Explanation: This is because of function attribute constructor will be called at the time of start, before main() function and function attribute destructor will be called at the time of exit, after the main() function.


Popular Posts