Monday, May 25, 2015

C : Program to display tabs , backspaces visible in an unambiguous way

In my earlier post, we have seen "C : Program to replace multiples spaces with a single space" , today lets modify the same code to display tabs, backspaces.

Below is the program which does this job.
 #include   
 int main()  
 {  
   char c;  
   printf("Enter a line to display tabs \n");  
   while((c=getchar()) != '\n')  
   {  
     if(c == '\t')  
     {  
         putchar('\\');  
         putchar('t');  
     }  
     putchar(c);  
   }  
   printf("\n");  
   return 0;  
 }  
In above program,
  • We read input character by character
  • Check if its tab (\t). If tab, we output (\\) followed by (t) character which displays \t.
  • If its not tab, we simply output the character.
Output of this program,
 mrtechpathi@mrtechpathi:~/Study/C/K_and_R$ ./a.out   
 Enter a line to display tabs   
 This  program     displays     the tabs     entered  
 This \t     program\t     displays\t     the tabs\t     entered  

Thursday, May 21, 2015

C : Program to replace multiples spaces with a single space

Earlier we have seen C program to count blanks and tabs , with using the same code, lets try to write another program which takes a line of words/characters and parses through it checking for multiple spaces and replaces them with single space.

For example, in  below line
This     line has      multiple        spaces    between     words.

Ideally while typing a sentence we leave a single space between word-to-word.  This sentence has multiple spaces which can be removed and replaced with single space by our program below.

This line has multiple spaces between words.
  #include <stdio.h>   
  int main()   
  {   
   int c;   
   printf("Enter a line to replace multiple spaces with single space\n");   
   /* Read character by character and prase till end of the file */  
   while((c=getchar()) != '\n')   
   {   
    if(c == ' ')   
    {   
     /* Notice semi-colon at end of below line. It reads a character and if its space  
      it discards it and read character again till its not a space*/  
     while( (c=getchar()) == ' ');   
      /* Now just output single space */  
      putchar(' ');   
    }   
    putchar(c);   
   }   
   printf("\n");   
   return 0;   
  }   
From above code,
  • Using while loop, we start reading character by character with getchar()
  • First character is read and checked for end of the line
  • If not End of the line ('\n'), check if it's a space
  • If its a space, discard spaces by reading them in a while loop.  Note semi-colon at end of the while loop.
  • Now output a single space and read next character.
  • Finally print a new line and return.
Output of this program,
 mrtechpathi@mrtechpathi:~/Study/C/K_and_R$ ./a.out   
 Enter a line to replace multiple spaces with single space  
 This program  replaces       multiple spaces    with   single  space  
 This program replaces multiple spaces with single space  


Monday, May 18, 2015

C : How to print line numbers and function names while debugging C programs

While debugging C program, we often add printf's to print some values or just a debug print. It would be additional advantage if you can print line number and function name when the program is too big to debug. If you are dealing with multiple files, its good idea to print the file name when you use printf isn't ?

In C, there are few preprocessor macros which allow you to print line numbers, function names and files names.

__LINE__           : Prints line number
__FUNCTION__: Prints function number
__FILE__            : Prints file number

These are predefined macros and part of the C/C++ standard. During preprocessing, they are replaced respectively by a constant string holding an integer representing the current line number and by the current file name.
 #include <stdio.h>  
   
 int main()  
 {  
   printf("\n This program prints line number %d\n",__LINE__);  
   printf("\n This program prints function name %s() \n",__FUNCTION__);  
   printf("\n This program prints file name %s\n",__FILE__);  
   return 0;  
 }  

Output of this program:
 mrtechpathi@mrtechpathi:~/Study/C/K_and_R$ ./a.out   
   
  This program prints line number 5  
   
  This program prints function name main()   
   
  This program prints file name print_line_function_file_name.c  
   

Others preprocessor variables :

__func__ : function name (this is part of C99, not all C++ compilers support it)
__DATE__ : a string of form "Mmm dd yyyy"
__TIME__ : a string of form "hh:mm:ss"

C : Program to count spaces and tabs

In earlier post "Character counting in C", we have written a program to count number of characters, lets extend this further and count blanks, tabs and newlines.
 int main()   
 {   
   double char_count;   
   char input_char;   
   int tabs_count=0,spaces_count=0;   
   char input_val;   
    
   printf("\n Input a line to count spaces and tabs \n");   
    
   /* Reading a character */   
   input_char = getchar();   
    
   /* In a for loop read characters till end of line is encountered */   
   for(char_count = 0; input_char != '\n'; ++char_count)   
   {   
     /* Check if input character is a space */     
     if(input_char == ' ')   
     {   
       /* if space, increment space variable count */          
       ++spaces_count;     
     }      
     /* else if input character is a tab */   
     else if(input_char == '\t')   
     {   
       /* if tab increment tab count */             
       ++tabs_count;      
     }   
     /* Read next character to check if its space or tab */   
     input_char = getchar();       
   }   
    
   /* Finally print number of spaces and tabs read */   
   printf("\n Your input contains %d spaces, %d tabs \n",spaces_count,tabs_count);   
    
   return 0;    
 }  
   
In above program,
  • We read a character
  • In a for loop till end of line is encountered, we check each character entered is a space (' ') or tab('\t').
  • Increment spaces_count and tabs_count variables accordingly
  • Finally when new line is encountered, we print the space count and tab count.
Output of this program :
 mrtechpathi@mrtechpathi:~/Study/C/K_and_R$ ./a.out   
   
  Input a line to count spaces and tabs   
 will be giving a tab now     just one tab behind  
   
  Your input contains 9 spaces, 1 tabs  

Linux : How to recursively touch files and folders in a directory

Guys today we will learn a small tip about touching multiple files / folders in a folder using Linux Terminal.

I assume you know about "touch" command in Linux if not please make sure you read its man page here.

You need to use below command to touch files/folders recursively.
 find . -exec touch {} \;  

Execute this command in the director in which you would like to perform this operation.

This command,

  • Finds each file
  • exec is used to invoke a subprocess "touch"
  • Curly bases and backward slash ending with semicolon as per syntax
Hope you find this tip useful.

Thursday, May 14, 2015

Character counting in C using for loop !!!

Yesterday we learnt about "Character Counting in C"  using while loop. Today in order to illustrate the same character counting in C, we will trying using for loop. We will also try to use float or double datatype to store the character count.

Lets get started ....
 #include <stdio.h>  
 int main()  
 {  
   double char_count;  
   printf("\n Input characters to count \n");  
   for(char_count = 0; getchar() != '\n'; ++char_count);  
   printf("\n You have typed %.0f character :) \n",char_count);  
   return 0;  
 }  

Above program,

  • Declares char_count as doube instead of int to make sure that the count is not overflow while taking the input. double takes relatively more time to overflow than int.
  • Requests user to input characters
  • Reads character by character using getchar() till end of the line
  • As you can see, there is no body for for loop here because whole operation of character counting is done in for loop itself. This is the beauty of for loop.
  • for loop and while loop they check the condition first and enter their body to execute the code which provides the programmer more flexibility of programming.
  • Once a line is entered, program exits by printing the character count.
  • One important thing to note here while printing is "%.0f",  usually printf uses %f for printing float or double. Since char_count is decalared as double, we use "%.0f" to supress the decimal point  and fraction part which is zero.
Now output of this program is..
 mrtechpathi@mrtechpathi:~/Study/C/K_and_R$ ./a.out   
  Input characters to count   
 This is single line of input  
  You have typed 28 character :)   


It's very simple but very useful snippet while coding !!

Wednesday, May 13, 2015

Character Counting in C

Here we are taking baby steps in c. Lets learn how to count the number of characters entered through stdin (standard input like keyboard).

We will try to code the program similar to my earlier posts.
 #include <stdio.h>  
 int main()  
 {  
   int c,count=0;  
   printf("Start your input \n");  
   c = getchar();  
   while(c != '\n')  
   {  
     putchar(c);  
     c = getchar();  
     ++count;  
   }  
   printf("\n Number of characters entered = %d\n",count);  
 }  

Though we can code above snippet in much simpler form, I have used my earlier programs code to count the number of characters in c.

From above program,
  • In a while loop, we take input from stdin
  • output the characater to stdin
  • read character
  • pre-increment the count value
  • Continue in the while loop till new line
  • When new line is encountered, we print the stdout and number of characters
Output of this program is below
 mrtechpathi@mrtechpathi:~/Study/C/K_and_R$ ./a.out   
 Enter Ctrl+C is to exit  
 Start your input   
 just a single line input  
 just a single line input  
  Number of characters entered = 24  
Note that we are printing the characters and number of characters when new line or carriage return is encountered.

About EOF (End of file) in C

Have you ever wondered what is EOF in "Exiting c program right after reading one line or after carriage return while reading input from stdin".

EOF (End of the file) is a macro which expands to an integer constant expression with type int and an implementation dependent negative value but is very commonly -1.

Below is a small snippet to print EOF in c.
 #include <stdio .h="">  
 int main()  
 {  
 printf("\n Value of EOF is %d\n",EOF);  
 return 0;  
 }  

Output of this program is:

 mrtechpathi@mrtechpathi:~/Study/C/K_and_R$ ./a.out   
  Value of EOF is -1  

Exiting c program right after reading one line or after carriage return while reading input from stdin

Yesterday, we learnt about "C program that copies its input to its output one character at a time" , if you observe the program mentioned in this post, you will observe that we are taking the input from stdin (standard input) and outputting to stdout (each line) till EOF (End of the file) is reached.

Ideally stdin EOF is like forever. So, we end up pressing Ctrl+C to exit the program. Now to modify this program to exit right after one line or after a carriage return, we need to do a simple modification.
Replace EOF with '\n'. Yes its as simple as that.

 #include <stdio.h>  
 int main()  
 {  
   int c;  
   printf("Program exits after new line or carriage return \n");  
   printf("Start your input \n");  
   c = getchar();  
   while(c != '\n')  
   {  
     putchar(c);  
     c = getchar();  
   }  
 }  

Only difference you observe is in the while condition, "while(c != EOF) is changed to while(c != '\n')".

Output will be as below.

 mrtechpathi@mrtechpathi:~/Study/C/K_and_R$ ./a.out   
 Enter Ctrl+C is to exit  
 Start your input   
 just one line input  
 just one line input  
Hope you understood this simple concept !!!

Tuesday, May 12, 2015

C program that copies its input to its output one character at a time

I have been blogging few interesting how-to articles which I learn in my daily professional life. Its been a while I haven't blogged any.So, thought of just adding atleast a program per day (very challenging isn't ?) along with how-to articles.

I will start with C-programming. As everyone know "Kernighan & Ritchie" (K&R) is the best book to learn C programming. I will using examples in this book.


If you want any C snippet meanwhile, just drop me a comment will try and get it done for you.  I cant promise, but will try my best to do code for you.


Frist lets start with "C program that copies its input to its output one character at a time"


 #include <stdio.h>  
 int main()  
 {  
   int c;  
   printf("Enter Ctrl+C is to exit\n");  
   printf("Start your input \n");  
   c = getchar();  
   while(c != EOF)  
   {  
     putchar(c);  
     c = getchar();  
   }  
 }  

Above program is exact copy of a program in K&R, I have just added two printf statements to it.

When you compile and run this program, it accepts whatever the character you input from the keyboard and print them once you press enter (new line / carriage return).

It does this task forever because we have used "While( c != EOF )" in our above code snippet.
This while statements will be true till you reach EOF of stdin (standard input) which is forever.

So, in order to exit from running your program, you need to press "Ctrl+C" on your keyboard together.

Now lets run and see, output will be as below
 mrtechpathi@mrtechpathi:~/Study/C/K_and_R$ ./a.out   
 Enter Ctrl+C is to exit  
 Start your input   
 we are  
 we are  
 trying to print  
 trying to print  
 character by character  
 character by character  
 ^C  
Hope you learnt something new :).

Set auto Indentation , shiftwidth and tab stop in Vim forever !!!

If you are looking for enabling auto indentation and to set tabstop to x characters, you are in right  place.

Open your .vimrc under your "/home/<user>" directory and add below lines
 filetype plugin indent on  
 set tabstop=4  
 set shiftwidth=4  
 set expandtab  
In above settings we have set 4 as tabstop and shiftwidth.
Now open a file with vim and your indentation and tabstop will work as expected.