tabs2spaces

cow 29.12.05 14:53

Muuntaa tabin neljäksi spaceksi

 Tekstiversio  Arvo: 2 (4 ääntä)  Äänestä: +  -
/**
    Kaikkihan toki tietävät, että oikea tapa sisentää on 4 spacea. Jos vahinko
    on jo kuitenkin päässyt käymään niin tämä ohjelma pelastaa ;)

    g++ tabs2spaces.cpp -o t2s
    ./t2s *.cpp *.h
*/


#include <fstream>
#include <string>
#include <iostream>
#include <cstdio>
#include <stdexcept>
#include <string.h>

static int errno;

inline std::string str_error() {
    return std::string(strerror( errno ));
}

int handle_file( const std::string& filename )
{
    std::string outfile = filename + ".tmp";
    std::ifstream in ( filename.c_str() );
    std::ofstream out( outfile.c_str() );

    if( !in.is_open() )
        throw std::ios_base::failure("Error opening input file: " + filename);
    if( !out.is_open() )
        throw std::ios_base::failure("Error opening output file: " + outfile);

    char c = in.get();
    int tabs = 0;
    while( !in.eof() ) {
        if(c == '\t') {
            out.write("    ", 4);
            ++tabs;
        }
        else
            out.write(&c, 1);
        in.get( c );
    }

    in.close();
    out.close();

    if( remove(filename.c_str()) == -1 )
        throw std::runtime_error("Error deleting the original file: " + str_error());
    if( rename(outfile.c_str(), filename.c_str()) == -1 )
        throw std::runtime_error("Error renaming file: " + str_error());
    return tabs;
}

int main(int argc, char** argv)
{
    for(int i=1;i<argc;++i) {
        try {
            std::string file = std::string(*(argv+i));
            std::cout << "Processing file " << file << "... ";
            int tabs = handle_file( file );
            std::cout << tabs << " tabs replaced" << std::endl;
        } catch( std::exception& e ) {
            std::cerr << e.what() << std::endl;
        }
    }
}
 

editoitu: 20:00 31.12.05
Ztane 19:57 31.12.05 
Onnistuu Unixeissa kätevästi myös perlillä:
perl -pi -e 's/\t/    /g' *.c

cappu 01:08 2.1.06 
Vimiä kun käyttää niin riittää komento:
:retab
editoitu: 17:02 10.1.06
cow 12:15 2.1.06 
perl -pi -e 's/\t/    /g' *.c

:retab

Näitä ollaankin mietitty, kiitoksia :)
exAtuu 12:32 2.1.06 
Höpöhöpö, oikea tapa sisentää on käyttää siihen tarkoitettua merkkiä, eli tabia.
Yazusan 15:36 4.1.06 
Oikein. Hyvässä editorissa on sitten vaihtoehtoja sille, että kuinka pitkinä tabit näytetään. Älkää käyttäkö huonoja editoreja.