removeLineEndSpace

本文介绍了一个用于去除文本文件中行尾空格的C程序。程序通过使用getline函数读取文件,并在循环中去除每一行末尾的空格、制表符和换行符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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 }

 

转载于:https://www.cnblogs.com/zengjfgit/p/4719951.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值