Linux下C语言代码的格式化


在 /usr/sbin/目录下创建format_sg文件,并更改其属性为777。

代码如下:

  1. #!/bin/sh  
  2. #      Author:  Guo Wenxue(guowenxue@gmail.com)  
  3. #        Date:  Fri Mar 18 17:56:44 CST 2011  
  4. #     Version:  1.0.0  
  5. # Description:  This shell script used to format all the source code in current forlder  
  6. #               and convert source code file format from windows to linux  
  7.    
  8.   
  9. find -iname "*.c" -exec dos2unix {} \;  
  10. find -iname "*.h" -exec dos2unix {} \;  
  11. find -iname "makefile" -exec dos2unix {} \;  
  12. find -iname "Makefile" -exec dos2unix {} \;  
  13.    
  14. # -npro   不要读取indent的配置文件.indent.pro  
  15. # -kr     使用Kernighan&Ritchie的格式  
  16. # -i4     设置缩排的格数为4  
  17. # -di28   将声明区段的变量置于指定的栏位(28)   
  18. # -ts4    设置tab的长度为4   
  19. # -bls    定义结构,"struct"和"{"分行  
  20. # -bl     if(或是else,for等等)与后面执行区段的”{“不同行,且”}”自成一行。  
  21. # -bli0   设置{ }缩排的格数为0   
  22. # -cli2   使用case时,switch缩排的格数  
  23. # -ss     若for或whiile区段只有一行时,在分号前加上空格  
  24. # -bad    在声明区段后加上空白行  
  25. # -bbb    块注释前加空行  
  26. # -bap    函数结束后加空行  
  27. # -sc     在每行注释左侧加上星号(*)。  
  28. # -bc     在声明区段中,若出现逗号即换行。  
  29. # -sob    删除多余的空白行  
  30. # -l100   非注释行最长100  
  31. # -ncs    不要在类型转换后面加空格  
  32. # -nce    不要将else置于”}”之后  
  33. # -nut    不要使用tab来缩进  
  34.   
  35. INDET_FORMAT="-npro -kr -i4 -ts4 -bls -bl -bli0 -cli2 -ss -bap -sc -sob -l100 -ncs -nce -nut"  
  36.    
  37. find -iname "*.c" -exec indent $INDET_FORMAT {} \;  
  38. find -iname "*.h" -exec indent $INDET_FORMAT {} \;  
  39.    
  40. find -iname "*.h~" | xargs rm -rf {} \;  
  41. find -iname "*.c~" | xargs rm -rf {} \;  

使用方法为:在要格式化代码的目录下运行format_sg

[root@ www.bkjia.com ]# format_sg
dos2unix: converting file ./tcp_process.c to UNIX format ...
dos2unix: converting file ./tcp_client.c to UNIX format ...
dos2unix: converting file ./tcp_server.c to UNIX format ...
dos2unix: converting file ./Makefile to UNIX format ...
dos2unix: converting file ./Makefile to UNIX format ...
[root@ www.bkjia.com ]#

相关内容