removeLineEndSpace

 1 /******************************************************************************
 2  *                          removeLineEndSpace
 3  *  声明:
 4  *      该程序是之前alignBySpace的逆向补充程序,去掉行尾的空格。
 5  *      
 6  *                                   2015-8-11 阵雨 深圳 南山平山村 曾剑锋
 7  *****************************************************************************/
 8 #include <stdio.h>
 9 #include <string.h>
10 #include <stdlib.h>
11 
12 int main ( int argc, char ** argv ) {
13 
14     int    ret                      = 0;
15     char  *tempFile                 = "generateFile.txt";
16     char  *readBuffer               = NULL;
17     size_t bufferSize               = 512;
18     int    readBufferIndex          = 0;
19 
20     if (  argc != 2  ) {
21         printf ( "USAGE:\n" );
22         printf ( "   removeLineEndSpace <file>.\n" );
23         return -1;
24     }
25 
26     FILE *readfile  = fopen ( argv[1], "r" );                         // only read
27     FILE *writefile = fopen ( tempFile, "w" );                        // only write
28 
29     /**
30      * man datasheet:
31      *    If *lineptr is NULL, then getline() will allocate a buffer for storing the line, 
32      *    which should be freed by the user program. (In this case, the value in *n is ignored.)
33      */
34     while ( ( ret = getline( &readBuffer, &bufferSize, readfile ) ) != -1 ) {
35 
36         readBufferIndex  = ret - 1; // index for real position
37 
38         while ( ( readBuffer [ readBufferIndex ] == ' ' ) ||          // del ' ', '\t', '\n' character
39                 ( readBuffer [ readBufferIndex ] == '\n' ) || ( readBuffer [ readBufferIndex ] == '\t' ) )  
40             readBuffer [ readBufferIndex-- ] = '\0';
41         
42         readBuffer [ readBufferIndex + 1 ] = '\n';
43 
44         fputs ( readBuffer, writefile );                              // write to file 
45 
46         bzero ( readBuffer,  ret );                                   // clean buffer
47     }
48 
49     free ( readBuffer );                                              // referrence getline()
50 
51     fclose ( readfile );
52     fclose ( writefile );
53 
54     remove ( argv[1] );                                               // delete source file
55     rename ( tempFile, argv[1] );                                     // tempfile rename to source file
56 }

 

posted on 2015-08-11 08:47  zengjf  阅读(323)  评论(0编辑  收藏  举报

导航