Monday 30 September 2013

Indent your C code within second

1 comment
GNU
    Indenting huge C program manually is difficult and time consuming. To reduce this effort we can use "GNU indent" tool. We can indent C program automatically with this tool. This tool is only design to indent C programs and not for C++.

Installation

    For  Debian OS(Ubuntu, OpenSuse) we can install using command given below.
sudo apt-get install indent
    For Redhat based OS(like Fedora, CentOS) we can install using command given below.
yum install indent
OR
    You can also download tar.gz and install manually using 
./configure
make
make install   (give command with root/sudoer privileges)

Uses

    As stated previously we can use this tool to automatically indent any C program.
Syntax:
indent prog1.c prog2.c
    This command will indent both the programs, if you want to save the files with different name to access the older files you can use the following syntax or command
indent prog1.c -o prog1_indent.c
    In this you can indent only one file at a time.
Below example shows the unintended C code(uint.c)

         #include"stdio.h"
   #include"stdlib.h"
      int main()
    {
     printf("This is unintended code")  ;
         return 0;
  }

After using intend command you get the intended code as shown below
intend unin.c

#include"stdio.h"
#include"stdlib.h"
int
main ()
{
  printf ("This is unintended code");
  return 0;
}

There are three by default styles of indenting the C program 
  1. gnu-style (it is by default)
  2. k-and-r-style (Kernighan & Ritchie style)
  3. linux-style
    For 2nd & 3rd style you have to specify it explicitly after as shown below
indent --linux-style  prog1.c
indent --k-and-r-style  prog1.c
    There are many options available to customize the above three styles out of which important option are given below you can find detail in the user manual  of indent.
-nsaf  => --no-space-after-for
-nsai  => --no-space-after-if
-nsaw => --no-space-after-while
-sob   => --swallow-optional-blank-lines (delete the extra blank lines)
-tsn    => --tab-sizen (we can set the tab size by changing the n)
(n is the length of the tab)
-nut   => --no-tabs (Use spaces instead of tabs)

    In some programs there are many "carriage return" (\r) characters are present indent tool will replace this "carriage return" to the "new line" (\n) which will cause unnecessary blank lines.
    To remove this unwanted "carriage return" (\r) from program we can use following command
cat prog1.c | tr -d "\r" >prog1.c
    In this command tr is used to translate or delete the characters.
After removing this "carriage return" you can use indent command to get proper output.



 





1 comment:

  1. Very useful blog.
    I failed to crack persistent's apti, becoz I didn't know the meaning of indentation at that time. So by then I know the importance of indentation very well. Thank you sir..

    ReplyDelete