This blog is under construction
Showing posts with label C Library. Show all posts
Showing posts with label C Library. Show all posts

Sunday, 3 February 2013

getopt_long_only example in C


Header file:
    getopt.h

Synopsis:
     int getopt_long_only (int argc, char *const *argv, const char *shortopts,
               const struct option *longopts, int indexptr);

Description:
     It is similar to getopt_long but it allows user to represent long option with single hypen (-) or double hypen(--).  Initially, it tries to parse the option with long option and if none of the long option matches, the option is parsed as short option.

Please know about getopt and getopt_long to get better understanding on getopt_long_only.


getopt_long_only function C example


  #include <stdio.h>
  #include <getopt.h>
  #include <string.h>
  #include <stdlib.h>
  static int myflag;
  struct option longopts[] = {
        {"setflag",   optional_argument, &myflag,  1},
        {"clearflag", no_argument,       &myflag,  2},
        {"list",      optional_argument, 0,      'l'},
        {"touch",     required_argument, 0,      'm'},
        {"rm",        required_argument, 0,      'r'},
        {"date",      no_argument,       0,      'd'}
  };

  int main (int argc, char **argv) {
        int i, ch, indexptr = 0, status = 0;
        char str[100];
        opterr = 0;
        while ((ch = getopt_long_only(argc, argv, "l::m:r:d",
                                longopts, &indexptr)) != -1) {
                switch (ch) {
                        case 0:
                                if (*(longopts[indexptr].flag) == 1) {
                                        status = 1;
                                        printf("long opt: %s\n",
                                                longopts[indexptr].name);
                                        printf("U've set status flag\n");
                                } else if (*(longopts[indexptr].flag) == 2) {
                                        status = 0;
                                        printf("long opt: %s\n",
                                                longopts[indexptr].name);
                                        printf("U've unset status flag\n");
                                }
                                break;
                        case 'd':
                                printf("short option - %c  long option - %s\n",
                                        ch, longopts[indexptr].name);
                                system("date");
                                break;
                        case 'l':
                                printf("short option - %c  long option - %s\n",
                                        ch, longopts[indexptr].name);
                                strcpy(str, "ls -l ");
                                if (optarg)
                                        strcat(str, optarg);
                                system(str);
                                break;
                        case 'm':
                                printf("short option - %c  long option - %s\n",
                                        ch, longopts[indexptr].name);
                                strcpy(str, "touch ");
                                strcat(str, optarg);
                                system(str);
                                break;
                        case 'r':
                                printf("short option - %c  long option - %s\n",
                                        ch, longopts[indexptr].name);
                                strcpy(str, "rm ");
                                strcat(str, optarg);
                                system(str);
                                break;
                        case '?':
                                if (optopt == 'r' || optopt == 'm')
                                        printf("Argument is mandatory for --%s\n",
                                                longopts[indexptr].name);
                                else if (isprint (optopt))
                                        printf("U have given an unknown option - %c\n",
                                                optopt);
                                else
                                        printf("Unknown Error-0x%08x\n", optopt);
                                break;
                        default:
                                exit(0);
                }
        }
        for (i = optind; i < argc; i++)
                printf("Redundant argument - %s\n", argv[i]);

        return 0;

  }



  Output:

  jp@jp-VirtualBox:$ ./a.out -setflag --touch file1 --list=file1
  long opt: setflag
  U've set status flag
  short option - m  long option - touch
  short option - l  long option - list
  -rw-r--r-- 1 jp jp 0 2013-02-03 13:16 file1
  jp@jp-VirtualBox:$ ./a.out -clearflag -date
  long opt: clearflag
  U've unset status flag
  short option - d  long option - date
  Sun Feb  3 13:16:35 IST 2013


Note:
If flag is not NULL, getopt_long or getopt_long_only returns 0 on parsing its corresponding long option and the flag will point to the value val in the structure option

static int myflag;
struct option longopt[] {
     {"setflag",    no_argument, &myflag,   9},
     {"clearflag", no_argument, &myflag, 10}
};

./a.out -setflag

In this case, getopt_long_only returns 0 on parsing the long option setflag and the flag "*(longopt[indexptr].flag)" will point to the value of val field (val is '9' here)in the structure option.

Saturday, 2 February 2013

getopt example in C

Header file:
    unistd.h

Synopsis:
     int getopt (int argc, char **argv, const char *options)

Description:
     getopt is used to parse command line options.  We need to know the below information to get clear idea on getopt.

int opterr
If opterr is non-zero, then getopt will print error message for unknown options or options with missing required argument.  If opterr is zero, then getopt will return '?' for unknown options or options with missing required argument.

int optopt
If getopt finds an unknown option character or an option with a missing required argument, then it stores that option character in optint.

int optind
Holds the index of the next element in argv and it will be set by getopt.

char *optarg
Pointer to the value of the required option argument or optional argument and it will be set by getopt.

Argument options indicates option characters. If the option character followed by single colon(:), it indicates that the option takes required argument.  If the option character followed by double colon(::), it indicates that the option takes optional argument.  And hypen '-' is used to recognize options.


getopt function C example



  #include <stdio.h>
  #include <unistd.h>
  #include <stdlib.h>
  int main (int argc, char **argv) {
        int i, ch;
        opterr = 0;
        while ((ch = getopt(argc, argv, "ab::c:")) != -1) {
                switch (ch) {
                        case 'a':
                                printf("Option 'a\'\n");
                                break;
                        case 'b':
                                printf("Option 'b\'");
                                if (optarg)
                                        printf(" & its Optional arg-%s", optarg);
                                printf("\n");
                                break;
                        case 'c':
                                printf("Option 'c\'");
                                printf(" & its required arg - %s\n", optarg);
                                break;
                        case '?':
                                if (optopt == 'c')
                                        printf("For option 'c\', argument is mandatory\n");
                                else if (isprint (optopt))
                                        printf("U have given an unknown "
                                                          "option - %c\n", optopt);
                                else
                                        printf("Unknown Error-0x%08x\n", optopt);
                                break;
                        default:
                                exit(0);
                }
        }
        for (i = optind; i < argc; i++)
                printf("Redundant argument - %s\n", argv[i]);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:$ ./a.out -boptionB -c optionC
  Option 'b' & its Optional arg-optionB
  Option 'c' & its required arg - optionC
  jp@jp-VirtualBox:$ ./a.out -a -c optionC optionD
  Option 'a'
  Option 'c' & its required arg - optionC
  Redundant argument - optionD
  jp@jp-VirtualBox:$ ./a.out -a -e
  Option 'a'
  U have given an unknown option - e


Notes:
Why optional argument is not parsed by getopt?
For optional argument, the argument should immediately follow the option character. There should not be any space between option and its argument.

Eg: 
./a.out -bhello
Here, option b will take the optional argument hello since we don't have space between the option and argument

./a.out -b hello
Here, option b won't take the optional argument hello since we have space between the option and argument.

backtrace_symbols_fd example in C


Header file:
    execinfo.h

Synopsis:
     void backtrace_symbols_fd (void *const *buffer, int size, int fd);

Description:
     backtrace() function gives us set of backtrace symbols(set of addresses).  Those addresses can be translated to set of strings and write those strings to the given file descriptor fd using backtrace_symbols_fd() function.  Argument buffer indicates the set of address(backtrace symbols) from backtrace() and size indicates the number of entries in the array.  And this function does not use malloc.


backtrace_symbols_fd function C example:



  #include<stdio.h>
  #include<execinfo.h>
  #include<stdlib.h>

  FILE *fp;
  void func5() {
        void *array[12];
        int size, i, fd;
        char **str;
        fp = fopen("./backtrace_info.txt", "a");
        fd = fileno(fp);
        fseek(fp, 0, SEEK_END);
        size = backtrace(array, 12);
        printf("Backtrace:\n");
        for (i = 0; i < size; i++) {
                printf("0x%08x\n", (int)array[i]); // printing symbols on output screen
        }

        /* converts address to string and writes the o/p to a file */
        backtrace_symbols_fd(array, size, fd);
        printf("No of level in backtrace:%d\n", size);
  }

  void func4() {
        func5();
  }

  void func3() {
        func4();
  }

  void func2() {
        func3();
  }

  void func1() {
        func2();
  }


  int main() {
        func1();
        return 0;
  }



  Output:

  jp@jp-VirtualBox:$ ls
  backtrace.c  backtrace_symbols.c  backtrace_symbols_fd.c
  jp@jp-VirtualBox:$ gcc -rdynamic backtrace_symbols_fd.c 
  jp@jp-VirtualBox:$ ./a.out
  Backtrace:
  0x080487d5
  0x0804884d
  0x0804885a
  0x08048867
  0x08048874
  0x08048881
  0x0015fce7
  0x080486e1
  No of level in backtrace:8
  jp@jp-VirtualBox:$ ls
  backtrace.c  backtrace_info.txt  backtrace_symbols.c  backtrace_symbols_fd.c 

  jp@jp-VirtualBox:$ cat backtrace_info.txt 
  ./a.out(func5+0x61)[0x80487d5]
  ./a.out(func4+0xb)[0x804884d]
  ./a.out(func3+0xb)[0x804885a]
  ./a.out(func2+0xb)[0x8048867]
  ./a.out(func1+0xb)[0x8048874]
  ./a.out(main+0xb)[0x8048881]
  /lib/libc.so.6(__libc_start_main+0xe7)[0x15fce7]
  ./a.out[0x80486e1]


Note:
why rdynamic option?
Eg: gcc -rdynamic backtrace_symbols.c
rdynamic is the linker option that makes the function names available to the program.  Basically, it instructs the linker to add all the symbols to the dynamic symbol table.

backtrace_symbols example in C


Header file:
    execinfo.h

Synopsis:
     char ** backtrace_symbols(void *const *buffer, int size);

Description:
     backtrace() function gives us set of backtrace symbols(set of addresses).  And those address can be translated to an array of strings using backtrace_symbols.  Argument buffer indicates the set of address(backtrace symbols) from backtrace() and size indicates the number of entries in the array.  And the return value of this function is the memory(pointer to a memory location) obtained via malloc and its user's responsibility to free the dynamically allocated block.


backtrace_symbols function C example


  #include<stdio.h>
  #include<execinfo.h>
  #include<stdlib.h>

  void func5() {
        void *array[12];
        int size, i;
        char **str;
        size = backtrace(array, 12);  // gets backtrace symbols in array
        printf("Backtrace:\n");
        for (i = 0; i < size; i++) {
                printf("0x%08x\n", (int)array[i]);
        }

        printf("\nBacktrace symbols:\n");
        str = backtrace_symbols(array, size);  // address to string conversion

        for (i = 0; i < size; i++)
                printf("%s\n", str[i]);
        printf("No of level in backtrace:%d\n", size);
        free(str);
  }

  void func4() {
        func5();
  }

  void func3() {
        func4();
  }

  void func2() {
        func3();
  }

  void func1() {
        func2();
  }


  int main() {
        func1();
        return 0;
  }



  Output:
  jp@jp-VirtualBox:$ gcc -rdynamic backtrace_symbols.c 
  jp@jp-VirtualBox:$ ./a.out
  Backtrace:
  0x080486dd
  0x08048785
  0x08048792
  0x0804879f
  0x080487ac
  0x080487b9
  0x00126ce7
  0x08048631

  Backtrace symbols:
  ./a.out(func5+0x19) [0x80486dd]
  ./a.out(func4+0xb) [0x8048785]
  ./a.out(func3+0xb) [0x8048792]
  ./a.out(func2+0xb) [0x804879f]
  ./a.out(func1+0xb) [0x80487ac]
  ./a.out(main+0xb) [0x80487b9]
  /lib/libc.so.6(__libc_start_main+0xe7) [0x126ce7]
  ./a.out() [0x8048631]
  No of level in backtrace:8

Note:
why rdynamic option?
Eg: gcc -rdynamic backtrace_symbols.c
rdynamic is the linker option that makes the function names available to the program. Basically, it instructs the linker to add all the symbols to the dynamic symbol table.


backtrace example in C


Header file:
    execinfo.h

Synopsis:
     int backtrace(void **buffer, int size);

Description:
     Gets backtrace for the calling thread and places the symbols(list of pointers) into the given buffer.  The size argument represent the number of void * elements that would fit into buffer.  And it returns the actual number of entries obtained in buffer.

backtrace function C example


  #include<stdio.h>
  #include<execinfo.h>
  #include<stdlib.h>

  void func5() {
        void *array[12];
        int size, i;
        size = backtrace(array, 12);
        for (i = 0; i < size; i++) {
                printf("0x0%08x\n", (int)array[i]);
        }
        printf("No of level in backtrace:%d\n", size);
  }

  void func4() {
        func5();
  }

  void func3() {
        func4();
  }

  void func2() {
        func3();
  }

  void func1() {
        func2();
  }

  int main() {
        func1();
        return 0;
  }




  Output:
  jp@jp-VirtualBox:$ ./a.out
  0x008048465
  0x00804844a
  0x00804843d
  0x008048430
  0x008048423
  0x00804840f
  0x00055dce7
  0x008048371
  No of level in backtrace:8




Sunday, 6 May 2012

strftime example in C

Header file:
    time.h

Synopsis:
     size_t strftime(char *str, size_t sz, const char *fmt,
                                        const struct tm *tp);

Description:
     Date and time information in *tp is formatted based on the format string in fmt and the result is placed inside the character array(pointer) str of size sz.

strftime function C example:


  #include<stdio.h>
  #include<time.h>
  int main() {
        time_t tp;
        struct tm *ts;
        int size;
        char str[100];
        tp = time(NULL);
        ts = localtime(&tp);
        size = strftime(str, 100, "%a %b %d %H:%M:%S %Y\n", ts);
        printf("%s", str);
        return 0;
  }




  Output:
  jp@jp-VirtualBox:~/cpgms/time$ ./a.out
  Sun May 06 00:01:55 2012



Saturday, 5 May 2012

gmtime example in C

Header file:
    time.h

Synopsis:
     struct tm *gmtime(const time_t *t1);

Description:
     It converts the calendar time t1 into UTC/GMT.


gmtime function C example:



  #include<stdio.h>
  #include<time.h>
  int main() {
        time_t tp;
        struct tm *t;
        char *str;
        tp = time(NULL);
        t = gmtime(&tp);
        str = asctime(t);
        printf("GMT:\n%s", str);
        str = ctime(&tp);
        printf("IST:\n%s", str);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/cpgms/time$ ./a.out
  GMT:
  Sat May  5 18:20:10 2012
  IST:
  Sat May  5 23:50:10 2012





ctime example in C

Header file:
    time.h

Synopsis:
     char *ctime(const time_t *tp);

Description:
     It coverts calendar time *tp to local time and returns the time in string format.


ctime function C example:


  #include<stdio.h>
  #include<time.h>
  int main() {
        time_t tp;
        char *str;
        tp = time(NULL);
        str = ctime(&tp);
        printf("%s\n", str);
        return 0;
  }




  Output:
  jp@jp-VirtualBox:~/cpgms/time$ ./a.out
  Sat May  5 23:42:02 2012



asctime example in C

Header file:
    time.h

Synopsis:
     char *asctime(const struct tm *tp);

Description:
     It converts the time in the structure *tp to a string format.


asctime function C example:


  #include<stdio.h>
  #include<time.h>
  int main() {
        struct tm *tp;
        time_t t;
        char *str;
        t = time(NULL);
        tp = localtime(&t);
        str = asctime(tp);
        printf("Output:%s\n", str);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/cpgms/time$ ./a.out
  Output:Sat May  5 22:45:09 2012



mktime example in C

Header file:
    time.h

Synopsis:
     time_t mktime(struct tm *tp);

Description:
     It takes the broken time (local time in the structure *tp) as parameter and returns us the calendar time in the same representation of time().


           struct tm {
               int tm_sec;         /* seconds */
               int tm_min;         /* minutes */
               int tm_hour;        /* hours */
               int tm_mday;        /* day of the month */
               int tm_mon;         /* month */
               int tm_year;        /* year */
               int tm_wday;        /* day of the week */
               int tm_yday;        /* day in the year */
               int tm_isdst;       /* daylight saving time */
           };


mktime function C example:


  #include<stdio.h>
  #include<time.h>
  int main() {
        struct tm *tp;
        time_t t;
        char str[100];
        t = time(NULL);
        tp = localtime(&t);
        t = mktime(tp);
        printf("Return value of mktime:%ld\n", t);
        sprintf(str, "%d/%d/%d   %d:%d:%d\n", tp->tm_mday, tp->tm_mon,
                1900+tp->tm_year, tp->tm_hour, tp->tm_min, tp->tm_sec);
        printf("Output:%s\n", str);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/cpgms/time$ ./a.out
  Return value of mktime:1336237515
  Output:5/4/2012   22:35:15

difftime example in C

Header file:
    time.h

Synopsis:
     double difftime(time_t t2, time_t t1);

Description:
     It returns the time difference between t1 and t2 in seconds.


difftime function C example:


  #include<stdio.h>
  #include<time.h>
  int main() {
        time_t tp, ret1, ret2;
        double time_diff;
        printf("time(NULL):%ld\n", ret1 = time(NULL));
        sleep(5);
        ret2 = time(&tp);
        printf("Return value: %ld\ntp:%ld\n", ret2, tp);
        time_diff = difftime(ret2, ret1);
        printf("Difftime:%lf\n", time_diff);
        return 0;
  }




  Output:
  jp@jp-VirtualBox:~/cpgms/time$ ./a.out
  time(NULL):1336236391
  Return value: 1336236396
  tp:1336236396
  Difftime:5.000000





time example in C

Header file:
    time.h

Synopsis:
     time_t time(time_t *tp);

Description:
     Returns current calendar time if tp is NULL or returns -1 on failure.  If tp is not NULL, then the return value is assigned to *tp.


time function C example:


  #include<stdio.h>
  #include<time.h>
  int main() {
        time_t tp, ret;
        printf("time(NULL):%ld\n", time(NULL));
        sleep(5);
        ret = time(&tp);
        printf("Return value: %ld\ntp:%ld\n", ret, tp);
        return 0;
  }




  Output:
  jp@jp-VirtualBox:~/cpgms/time$ ./a.out
  time(NULL):1336234593
  Return value: 1336234598
  tp:1336234598



clock example in C

Header file:
    time.h

Synopsis:
     clock_t clock(void);

Description:
     It returns the processor time used by the program at the time of execution(return value is clock ticks).  clock()/CLOCKS_PER_SEC gives the time in seconds and it returns -1 on failure.


clock function C example:


  #include<stdio.h>
  #include<time.h>
  int main() {
        clock_t clk_val;
        int i;
        while(clock() < 5 * CLOCKS_PER_SEC / 100){}
        clk_val = clock();
        printf("Clocks per second: %ld\n", CLOCKS_PER_SEC);
        printf("Processor time used from the beginning "
                       "of program execution: %ld\n", clk_val);
        return 0;
  }




  Output:
  jp@jp-VirtualBox:~/cpgms/time$ ./a.out
  Clocks per second: 1000000
  Processor time used from the beginning of program execution: 50000




Monday, 30 April 2012

ldiv example in C

Header file:
    stdlib.h

Synopsis:
     ldiv_t div(long numerator, long denominator);

Description:
     It calculates the quotient and remainder of numerator/denominator and its results are stored in the long members quot and rem fields of the structure div_t.


ldiv function C example:


  #include<stdio.h>
  #include<stdlib.h>
  int main() {
        long num, denom;
        ldiv_t res;
        printf("Enter the value for numerator and denominator:");
        scanf("%ld%ld", &num, &denom);
        res = ldiv(num, denom);
        printf("%ld/%ld = %ld\n", num, denom, res.quot);
        printf("Remainde:%ld\n", res.rem);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/cpgms/stdlib$ ./a.out
  Enter the value for numerator and denominator:123123213 43543
  123123213/43543 = 2827
  Remainde:27152


div example in C

Header file:
    stdlib.h

Synopsis:
     div_t div(int numerator, int denominator);

Description:
     It computes the quotient and remainder of numerator/denominator and stores them correspondingly in the quot and rem fields of the structure div_t.


div function C example:


  #include<stdio.h>
  #include<stdlib.h>
  int main() {
        int num, denom;
        div_t res;
        printf("Enter the value for numerator and denominator:");
        scanf("%d%d", &num, &denom);
        res = div(num, denom);
        printf("%d/%d = %d\nRemainde:%d\n", 
                   num, denom, res.quot, res.rem);
        return 0;
  }




  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for numerator and denominator:100 23
  100/23 = 4
  Remainder:8



labs example in C

Header file:
    stdlib.h

Synopsis:
     long int labs(long int num)

Description:
     It returns the absolute value of its long integer argument num.


labs function C example:


  #include<stdio.h>
  #include<stdlib.h>
  int main() {
        long no;
        printf("Enter a number:");
        scanf("%ld", &no);
        no = abs(no);
        printf("Output: %ld\n", no);
        return 0;
  }




  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter a number:-234324324
  Output: 234324324