Skip to main content

Posts

Showing posts with the label C programming

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      * str...

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 tes...

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 ...

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); ...

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 */      (*tem...

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){   ...

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 *)...

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); }

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 =...