Posted By

Zufolek on 12/27/09


Tagged


Versions (?)

Remove trailing blanks from files


 / Published in: C
 

Simple prog for removing trailing blanks. Not for use with binary, compressed, or encoded files. Please make backups of your files.

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <windows.h>
  4.  
  5. char*mytmpfile="notrail.tmp";
  6.  
  7. void err(char*text){
  8. if(!text)text="Can't open file";
  9. MessageBox(
  10. 0,
  11. text,
  12. "NoTrail Error",
  13. MB_ICONERROR | MB_OK
  14. );
  15. exit(1);
  16. }
  17.  
  18.  
  19. static inline void replace(char*s){
  20. remove(s);
  21. rename(mytmpfile,s);
  22. }
  23.  
  24.  
  25. static inline void notrail(char*filename){
  26. FILE*i,*o;
  27. unsigned long int saved=0;
  28. unsigned long int n;
  29. int c;
  30. int b;
  31. i=fopen(filename,"rt");
  32. if(!i)err(0);
  33. o=fopen(mytmpfile,"wt");
  34. if(!o)err(0);
  35. do{
  36. c=getc(i);
  37. if(c==EOF)break;
  38. if(c==32){
  39. n=1;
  40. while((c=getc(i))==32)++n;
  41. if(c!='\n'&&c!=EOF){
  42. do putc(' ',o);
  43. while(--n);
  44. }else saved+=n;
  45. }
  46. b=c!=EOF;
  47. if(b)putc(c,o);
  48. }while(b);
  49. fclose(o);
  50. fclose(i);
  51. if(saved){
  52. char text[32];
  53. sprintf(text,"Saved %lu bytes\n",saved);
  54. n=MessageBox(
  55. 0,
  56. text,
  57. filename,
  58. MB_ICONASTERISK | MB_OKCANCEL
  59. );
  60. if(n==IDOK){
  61. replace(filename);
  62. return;
  63. }
  64. }
  65. remove(mytmpfile);
  66. }
  67.  
  68.  
  69. int main(int argc,char**argv){
  70. if(argc<2){
  71. MessageBox(
  72. 0,
  73. "Removes trailing blanks. To use, close this"
  74. " window and drag and drop one or more"
  75. " files onto the program's icon.",
  76. "NoTrail by Zufolek 2009",
  77. MB_ICONINFORMATION | MB_OK
  78. );
  79. return 0;
  80. }
  81. while(--argc)notrail(*++argv);
  82. return 0;
  83. }

Report this snippet  

You need to login to post a comment.