Thursday, January 12, 2012

Enhance Coding Experience at Linux








Hi friends,

I am back again with a good utility for programmers.Are you bored of putting same header files again  and again while writing a new code every time ???. I was wondering if it is possible whenever i open a file with '.c' or '.cpp' extension my system open the file and put the standard headers (at least frequently used like stdio.h) in it automatically and i need not to waste time writing them.

I discussed the same with my good friend Utkarsh Srivastav , he then came with a very good script which served my purpose.I am Sharing the same script here and how you can make use of the script to the maximum.

Step 1:
Save this Script as coding.sh in your home directory ( in my case /home/amol)

file=$1
x=${file##*.}
if [ "$x" == "c" ]
then
 if cat $1 > /dev/null 2> /dev/null
 then echo ""
 else
 echo "#include   #YOUR C TEMPLETE HERE
#include

#include
#include
#include

int main()
{
        
 return 0;
}
" >> $1
 fi
elif [ "$x" == "cpp" ]
 then
 if cat $1 > /dev/null 2> /dev/null
 then echo ""
 else
 echo "#include  #YOUR C++ TEMPLETE HERE
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;

typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int UINT;
int gcd( int a, int b ) {  if( !b ) return a;  return gcd( b, a % b ); }

int main()
{
       
 
 return 0;
} 
"  >> $1
 fi
fi
gedit $1 &
#Ignore line below, it is coming as blogger is treating headers as HTML tags :P


Step 2:
Open the .bashrc file of your system located in home directory
Amol@Dreamer-PC:~$ gedit .bashrc&

Step 3:
Add the following line in your .bashrc file
alias code="bash /home/amol/coding.sh"
Now 'code' will now appear as a command for the users to open the files :)

now whenever you will type
Amol@Dreamer-PC:~$ code myfile.c
it will open the new file in gedit with the headers already written in it.

similarly for '.cpp' files .
It will work for the existing files as well by opening the in gedit without modifying anything in it.

Now few lines explaining how Script works,first we are finding the extension of the using Shell Parameter Expansion ,then we are checking if the extension is '.c', if it is then then we are adding our template only if it is empty. Similar logic for '.cpp' extension,and finally we are opening the file using gedit as the background process.

You can make the changes in the script as per your requirements like the template or the editor or you may even add some more languages to it.

Hope all the linux coders will find this utility useful.


2 comments: