checkSpacing.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. ** This program checks for formatting problems in source code:
  3. **
  4. ** * Any use of tab characters
  5. ** * White space at the end of a line
  6. ** * Blank lines at the end of a file
  7. **
  8. ** Any violations are reported.
  9. */
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #define CR_OK 0x001
  14. #define WSEOL_OK 0x002
  15. static void checkSpacing(const char *zFile, unsigned flags){
  16. FILE *in = fopen(zFile, "rb");
  17. int i;
  18. int seenSpace;
  19. int seenTab;
  20. int ln = 0;
  21. int lastNonspace = 0;
  22. char zLine[2000];
  23. if( in==0 ){
  24. printf("cannot open %s\n", zFile);
  25. return;
  26. }
  27. while( fgets(zLine, sizeof(zLine), in) ){
  28. seenSpace = 0;
  29. seenTab = 0;
  30. ln++;
  31. for(i=0; zLine[i]; i++){
  32. if( zLine[i]=='\t' && seenTab==0 ){
  33. printf("%s:%d: tab (\\t) character\n", zFile, ln);
  34. seenTab = 1;
  35. }else if( zLine[i]=='\r' ){
  36. if( (flags & CR_OK)==0 ){
  37. printf("%s:%d: carriage-return (\\r) character\n", zFile, ln);
  38. }
  39. }else if( zLine[i]==' ' ){
  40. seenSpace = 1;
  41. }else if( zLine[i]!='\n' ){
  42. lastNonspace = ln;
  43. seenSpace = 0;
  44. }
  45. }
  46. if( seenSpace && (flags & WSEOL_OK)==0 ){
  47. printf("%s:%d: whitespace at end-of-line\n", zFile, ln);
  48. }
  49. }
  50. fclose(in);
  51. if( lastNonspace<ln ){
  52. printf("%s:%d: blank lines at end of file (%d)\n",
  53. zFile, ln, ln - lastNonspace);
  54. }
  55. }
  56. int main(int argc, char **argv){
  57. int i;
  58. unsigned flags = WSEOL_OK;
  59. for(i=1; i<argc; i++){
  60. const char *z = argv[i];
  61. if( z[0]=='-' ){
  62. while( z[0]=='-' ) z++;
  63. if( strcmp(z,"crok")==0 ){
  64. flags |= CR_OK;
  65. }else if( strcmp(z, "wseol")==0 ){
  66. flags &= ~WSEOL_OK;
  67. }else if( strcmp(z, "help")==0 ){
  68. printf("Usage: %s [options] FILE ...\n", argv[0]);
  69. printf(" --crok Do not report on carriage-returns\n");
  70. printf(" --wseol Complain about whitespace at end-of-line\n");
  71. printf(" --help This message\n");
  72. }else{
  73. printf("unknown command-line option: [%s]\n", argv[i]);
  74. printf("use --help for additional information\n");
  75. }
  76. }else{
  77. checkSpacing(argv[i], flags);
  78. }
  79. }
  80. return 0;
  81. }