Skip to main content

Posts

Showing posts from 2011

few program needs to link required library in gcc

lets consider simple program below this program will compile but linker fails to find definition of cos and sin functions #include<stdio.h> #include<math.h> #include <stdlib.h> #define PI 3.142 int main() {  double sinval, cosval;  int x=2;  sinval = sin(PI/x);  cosval = cos(PI/x);  printf("sin and cos of PI/x  is %lf %lf\n", sinval, cosval);  return 0; } followings link errors we will hit, since linker can't able to resolve the definition of cos() and sin() shiv@ubuntu:~$ gcc mat1.c /tmp/ccHOvWsZ.o: In function `main': mat1.c:(.text+0x2a): undefined reference to `sin' mat1.c:(.text+0x4b): undefined reference to `cos' collect2: ld returned 1 exit status so to fix the above issue we need to link the required library, here cos() and sin() are present in the math library so we need to link math library with the program as follows gcc  mat1.c -lm -lm will link the math library with above program so program build properly, so as li

C Program to Simulate Linux Cat command

/*  * C program to Simulate Implementation of  Linux *cat* command  * This program will not handle redirection  * you can try to improve this program to handle redirection of file contents  */ #include<stdio.h> #include<string.h> #define MAX_FILE_NAME_CHARS 255 int main(int argc, char *argv[]) {  FILE *fp;  char file_name[MAX_FILE_NAME_CHARS], ch;  int i;  /*   * after creating a.out, rename it as mycat for our own cat command   * and it usage is same as standard cat command   */  if(argc<1){     printf("Usage mycat <filename> \n");     return 0;  }  /*   * cat handles more than one file   * so we need this loop to handle all the files provided   * on command line   */  for(i=1; i<=argc;i++){     /* no need of copy but for understanding purpose, i have created      * string for each file name      */     strncpy(file_name, argv[i], MAX_FILE_NAME_CHARS);     fp=fopen(file_name, "r");     if(fp == NULL) {   

Simple program to illustrate variadic macros In C

/*  * C99 has  support of variable arguments in macros statement  * (called variadic macro) just like variable argument function, Macros also   * can be of variable number of augments  * This program illustrate variadic macros  */ #include <stdio.h>   /*   * Simple Macro definition   * which allows to print whatever the way you want   *  in Macro definition "..." indicates variadic macro, OP() definition is    * mixture of named args and variable number of aguments, it is possible   * to have macro of complete variable number of args   * like DISPLAY in below example   */ #define OP(format, exp, ...)  printf(format, exp, ##__VA_ARGS__) #define DISPLAY(...)    printf(__VA_ARGS__) int main() {  int a=3, b=4, c=5;  OP("%s %d\n", "Result after add", a+b);  OP("%s %d %s %d\n", "Result after add", a+b+c, "Result after sub", a-b);  OP("%s\n", "This is test program");  OP("%s %f\n", "

C Program to find Armstrong numbers between range m and n

/*  * Program to print Armstrong number between range m and n  * Armstrong  number is nothing but sum of cubes of digits of number is  * equal to the number  * ex: 153 is Armstrong number since 1^3+5^3+3^3=153  * there are very few numbers hold above property; execute   * below program to find all numbers  * b/w m and n  */ #include <stdio.h> void is_armstrong(int num) {   int sum=0, n, d;   n=num;   while(n){   d=n%10;  /* extract digits of number*/   sum=sum+(d*d*d);  /*take sum of them */   n=n/10;  }  if(sum == num)  /*sum is same as number then it is Armstrong number*/     printf("%d\n", sum); } int main() { int i,n,m; printf("Enter range \n"); scanf("%d%d", &m, &n);  for(i=m;i<=n;i++){    is_armstrong(i);  } return 0; }

Interactive C program to Swap bits in 32 bit integer

/*  * Program to swap bit in given 32 bit Integer number  */ #include<stdio.h> int main() {  int a;  int b1, b2;  printf("Enter numbers \n");  scanf("%d", &a);  printf("Enter bit numbers to be swapped\n");  scanf("%d%d", &b1, &b2);  if(b1 >=31 || b2>=31){     printf("Invalid bit positions(valid are 0 - 31)\n");     return 0;  }    if((a&(1<<b1)) && !(a&(1<<b2))){     /* bit number b1 is set but b2 is not      * to swap just unset b1 and set b2      */       a=a & ~(1<<b1);       a=a | (1 << b2);  } else if(!(a&(1<<b1)) && (a&(1<<b2))){        /* bit b1 is not set(zero) and bit b2 is set         * so to swap set b1 and clear b2         */       a=a | (1<<b1);       a=a & ~(1<<b2);  } else {      /* given both bits are set/clear in number so nothing to be done*/  } printf("Number after bit swap is %d\n", a); return 0;

Find size of structure variable(any variable) without using sizeof operator in C

This is one of the interview question, beginners could note, below is one of the way how we can find size of structure without using sizeof operator in C It is explained with simple program as follows #include<stdio.h> struct test {  int a;  char c;  double d; }; int main() { struct test *p; int size=0; /*  * initialize struct pointer with  * zero after type casting it to of type (struct test *)  */ p=(struct test *)0; /* by adding one to p gives size of struct */ size =(int)(p+1); printf("without using sizeof %d\n", size); /* verify result with sizeof operator */ printf("with using sizeof %d\n", sizeof(struct test)); return 0; } same way we can find size of other variables as well :-)

C program to find size of text file

/*  *Program to find size of text file  */ #include<stdio.h> #define LINE 80 int main(int c, char *argv[]) { /* fp is file pointer, once we open file, it is pointer to opened file */  FILE *fp;  char ch;  unsigned int size=0; /* Open file for reading   * argv[0] is executable program name and argv[1] is first   * argument given after executable file  */  fp=fopen(argv[1],"r");  /* if we get NULL as return value from fopen()   * it means, program is not able to open file or   * file may not existed ? or given file path will be wrong   */  if(fp == NULL){     printf("Can't open file\n");     return 0;  }  /*   * read characters from file and check size   */  while((ch = fgetc(fp)) != EOF){  /* we can add 1 to size every time but better to use sizeof to avoid issues */        size=size+sizeof(ch);  } printf("%u\n", size);  /*   * once we done with file we need to close it   */ fclose(fp); return 0; }

Program to Swap Adjecent nodes in single linked list

shiv@ubuntu:~/ds/list$ cat   altxchangenode.c /*  * program to Xchange or swap all the adjecent nodes(not node data) in the single linked list  */ #include<stdio.h> #include<stdlib.h> #define MAX 10 struct list {  int d;  struct list *next; }; /*  * function to swap 2 adjecent nodes(linkes) in the list  */ void xchangenodes(struct list **head, struct list **ne, struct list **tm) {   struct list *temp, *x1, *x2;   if(*tm == NULL){      return;   }   if((*tm)->next && (*tm)->next->next){       /*next node when more than 3 nodes present in the list */      temp=(*tm)->next->next;   } else if((*tm)->next){       if(*head != NULL) {   /* only two nodes present in the list */          (*ne)->next = (*tm)->next;          (*ne)->next->next = *tm;          (*tm)->next = NULL;       } else {           /* last iteration where last 2 nodes we need to swap */          *head=(*ne)->next;          (*head)->next =*tm;          (*tm)->next

C program to delete node from single linked list when just address of the previous node to be deleted is given

shiv@ubuntu:~/ds/list$ cat deln.c /*  * C Program to delete node in the single linked list, when address of the  *previous  node to be deleted is given  */ #include <stdio.h> #include <stdlib.h> struct list {     int d;     struct list *next; }; /*  * function to delete node when just address of the node to be  * deleted is given in the single linked list  */ void deletenode(void **ptr) {   struct list **temp, *del;   if(*ptr == NULL) {      printf("Invalid pointer\n");      return;   }   temp= (struct list **)ptr;   printf("The address of previous node of the node to be deleted is %p data %d\n", *temp, (*temp)->d);   if((*temp)->next && (*temp)->next->next){      /* any node apart from node before last or last node in the list */      (*temp)->d = (*temp)->next->d;      del = (*temp)->next;      (*temp)->next = (*temp)->next->next;      free(del);   } else if((*t

C Program to create sorted single linked list from given unsorted array

shiv@ubuntu:~/ds/list$ cat  tarr_to_sortlist.c  /*  * Program to create sorted list from given unsorted array  */ #include<stdio.h> #include<stdlib.h> #include<malloc.h> #define MAX 10 struct list { int d; struct list *next; }; int main() {  /* example array to test program */  int a[MAX]={4,1,5,6,10,9,3,2,7,8};  int  i;  struct list *head=NULL, *temp, *insert; /*loop to get all array elements*/ for(i=0;i<MAX;i++) { temp= malloc(sizeof(struct list)); if (temp == NULL) {         printf("Can't allocate memory\n");         exit(0); } temp->d = a[i]; temp->next = NULL;    /* first node in list */    if( head == NULL) {       head = temp;    } else {        / * second node in the list */        if( head->next == NULL){            if(head->d > temp->d){               temp->next = head;               head= temp;            } else {                   head->next = te

Simple program to create Zombie @ Linux

shiv@ubuntu:~/ds/unix$ cat zmb.c /*  * simple program to create a Zombie  * ps command display Zombie with Z under flags in ps output  */ #include<stdio.h> #include<unistd.h> #include<stdlib.h> int main() {  pid_t pid; /* create child process */  pid=fork();   if(pid == 0){    /* child process exits and becomes Zombie     */    exit(0);  } sleep(20); printf("Done ....\n"); return 0; }

simple program to create Orphan process

shiv@ubuntu:~/ds/unix$ cat  orp.c /*  * Program to create orphan process @ Linux  * getpid() gives process PID and   * getppid() gives process's parent ID   * here main() process ID is parent id is current shells PID  * once process becomes orphan it is adopted by init process(it's PID is 1)  */   #include<stdio.h> #include<unistd.h> int main() {  pid_t p; /* create child process */  p=fork();  if(p==0) {     /* fork() returns Zero to child */     sleep(10);  }  printf("The child process pid is %d parent pid %d\n", getpid(), getppid()); /*parent/child waits for 20 secs and exits*/  sleep(20);  printf("\nProcess %d is done its Parent pid %d...\n", getpid(), getppid());  return 0; } O/p shiv@ubuntu:~/ds/unix$ ./a.out The child process pid is 2575 parent pid 1922 The child process pid is 2576 parent pid 2575 Process 2575 is done its Parent pid 1922... shiv@ubuntu:~/ds/unix$ Process 2576 is done its Parent pid 1...

few ways Program to Find the machine is little endian or Big endian

following are the ways to find machine is little endian or big endian , and how to verify my program is working fine? # 1 /* program to find machine is little endian  or little endian */ #include<stdio.h> int main() {  int x=0x12345678;  char *p;  p=(char *)&x;  if(*p == 0x78) {     printf("Little endian \n");  } else {    printf("Big endian \n");  } return 0; } #2 /* another correct way is using unions */ int main() { union e {        int x;        char y; }; union e p1; p1.x=0x12345678; if(p1.y == 0x78) {     printf("Little endian \n");  } else {    printf("Big endian \n"); } return 0; } #3 below is same as #1 with more simplified shiv@ubuntu:~/ds/misc$ /* following is not correct way to find the machine */  #include<stdio.h> int main() { int num=1; if(*(char *)&num == 1)  {     printf("Little\n");  } else {    printf("Big endian\n"); } } below

Interactive C program to Simulate Queue operations on Circular Queue using arrays

shiv@ubuntu:~/ds/queue$ cat  circularq.c /*  * Interactive program to simulate Circular Queue using arrays  */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define MAX_SIZE 5 #define FALSE 0 #define TRUE 1 /* Insert element into Queue */ int insert(int cq[], int e, int head, int *tail) {   if((*tail + 1)%MAX_SIZE == head){       printf("Queue is full\n");       return FALSE;   }   cq[*tail]=e;  *tail = (*tail +1)% MAX_SIZE;   return TRUE; } /* Delete element from queue */ int  del(int cq[], int *head, int tail) {  if(tail == *head) {     printf("Queue is empty");     return FALSE;  }  printf("deleted %d\n", cq[*head]);  *head = (*head + 1)%MAX_SIZE;  return TRUE;      } /* Display elements in the queue */ void display(int cq[], int h, int t) {   int i=h;  printf("Queue elements are ..\n");  for (i=h; i != t; i=(i+1)%MAX_SIZE)  {      printf("%d\n", cq[i]

Interactive C program to demonstrate Circular single linked list

/* Program to Demonstrate Circular single linked list */ #include <stdio.h> #include <stdlib.h> /* Circular single linked list */ struct clist { int data; struct clist *next; }; typedef struct clist *CL; /* inserting elements into Circular list just after first(head) node */ void insert(CL *head) {  CL temp;  int e;  temp=malloc(sizeof(struct clist));  if(temp == NULL){     printf("Can't allocate memory\n");     return;  }  printf("Enter element\n");  scanf("%d", &e);  temp->data = e;  if(*head == NULL){      *head = temp;      (*head)->next = temp;  } else {     temp->next = (*head)->next;    (*head)->next =temp;     *head =temp;      } }   /* Displaying elements in list */ void display(CL head) {  CL temp;  if(head == NULL) {     printf("Empty list \n");     return;  }  temp = head;  printf("Elements are \n"); do {      /* it circular list after he

program to different ways to swap values of two variables without using temporary variables

shiv@ubuntu:~/ds/list$ cat swap.c /*  * Program to swap values of two variables  * without using temporary variables  */ #include <stdio.h> /*  * swaping values two variables using arithmetic  * operators  */ void swap(int *x, int *y) {   *x = *x + *y;   *y = *x - *y;   *x = *x - *y; } /*  * swaping values of variables using  * XOR oprations  */ void swap_xor(int *x, int *y) {   *x = *x ^ *y;   *y = *x ^ *y;   *x = *x ^ *y; } int main() {  int x, y, a, b;  x=20;  y=30;  swap(&x, &y);  printf("\nafter swap x=%d and y=%d", x, y);  a=50;  b=100;  swap_xor(&a, &b);  printf("\nafter swap a=%d and b=%d\n", a, b); }

How to add /proc file system entry for the module, illustrated here

here is simple example to demonstrate adding /proc file system entry for the module, as follows shiv@ubuntu:~/ds/linx$ cat heloproc.c /*  * Kernel program demo to illustrate how to create/add entry to  * /proc file system  */ #include <linux/init.h> #include <linux/module.h> #include <linux/proc_fs.h> /* Module license */ MODULE_LICENSE("Dual BSD/GPL"); /*  * This is the service routine for added /proc entry  * when user try to look into /proc/<entry added> this routine will be executed  *  * char *buf - below is page allocated by kernel and passed to service routine  * eof and start would be used only when using /proc for  * getting more than one page (usually page is 4KB)  * for complete info you could refer linux docs  */ int demo_read_fs(char *buf, char **start, off_t offset, int count, int *eof, void *data) {   int len=0;  len = sprintf(buf, "This is Demo proc fs creation\n\n");  return len; } /*  * cre

sample program to demonstrate writing daemon program in C and linux

/*  * program to demonstrate writing daemon programs in C and linux  * This Daemon print(adds) time or date every minute, depending on  * user choice t or d to syslog file  */ #include <stdio.h> #include <sys/stat.h> #include <syslog.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <time.h> #include <stdlib.h> /*  * parameters to daemon using argc and argv  */ int main(int c, char *argv[]) {  pid_t pid, sid;  char ch;  time_t t;  char  buf[80];  struct tm *ts; /*  * this daemon expects one argument  * as daemon name is count number 1 and one arg to daemon  * so checking for count <2  */  if(c<2) {     printf("usage: <program name> d | t \n");     return 0;  }  ch = argv[1][0];  printf("The choice is %c\n", ch);  if (!((ch =='d') || (ch == 't'))) {      printf("Not right choice ..\n");      return 0;  }  /* step 1 of da

Interactive C program to implement Instert begining, delete begining and reversing of single linked list

shiv@ubuntu:~/ds/list$ cat   revlist.c /*  * Interactive C program to simulate following operations  * on single linked list  * 1. insert begining of the list  * 2. display data in the list (traversing)  * 3. delete element at begining of the list  * 4. reverse the elements in single linked list  */ #include<stdio.h> #include<stdlib.h> struct list { int data; struct list *next; }; typedef struct list *L; /* function to insert element into list */ void insert(L *head) {  /* look for typedef temp is pointer not variable,   *  same will apply to all   */  L temp;  temp=malloc(sizeof(struct list));  if(!temp) {     printf("Can't allocate memory\n");     return;  }  printf("Enter element to insert\n");  scanf("%d", &temp->data);  temp->next = NULL;  if(*head == NULL) {     *head = temp;  } else {     temp->next = *head;     *head = temp;  } } /* function to display elements in the list */ vo