删除windows代码文件中的'^M'

时间:2023-01-18 18:03:56

有时从windows中copy过来的代码文件中会有很多'^M'(回车)字符,
这使代码看起来很不整洁。这里分享一个简单的处理办法。

思路:

找到文件中的'^M'字符,并全部替换为space。最后用indent整理代码。
'^M'的ascii是13。
代码:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#define M_ASC 13

int main(int argc, char **argv)
{
	char ch, *path;
	int res;
	FILE *f;
	long pos;

	if (argc > 1)
		path = argv[1];

	f = fopen(path, "r+");
	if (!f) {
		fprintf(stderr, "Open() %s ERROR(%s)\n", path, strerror(errno));
		exit(EXIT_FAILURE);
	}

	do {
		pos = ftell(f);
		ch = fgetc(f);
		if (ch == M_ASC) {
			fseek(f, pos, SEEK_SET);
			fputc(' ', f);
		}
	} while (ch != EOF);

	fclose(f);
	exit(EXIT_SUCCESS);
}
用indent工具整理代码:
#!/bin/sh
PARAM="-npro -kr -i8 -ts8 -sob -l80 -ss -ncs -cp1"
indent $PARAM "$@"


--
其他方法:
perl-> http://www.perlmonks.org/?node_id=183567

#!/usr/bin/perl -w 

use strict;
my $out;

if(@ARGV!=1 && @ARGV!=2){
    print "Usage:\n\t$0 input [output];\n";
    exit;
}

open(IN, "<$ARGV[0]") or die "couldn't open $ARGV[0]: $!";

if(<IN>=~m/(^#!.*perl.*)/){
    $out.=$1;
}

while(<IN>){
    chomp;
    chop;
    $_.="\n";
    $out.=$_;
}

close IN;    

if(@ARGV==1){
    unlink $ARGV[0];
    open(OUT,">$ARGV[0]") or die "couldn't open $ARGV[0]: $!";
}
elsif(@ARGV==2){
    open(OUT,">$ARGV[1]") or die "couldn't open $ARGV[1]: $!";
}

print OUT $out;
close OUT;