|
Back in the DOS days, the IDE I was using provided a cool options that converted tabs to spaces once you saved the file.
Also, in the same years I wrote a small and unoptimized program that converted tabs to a specified number of spaces in text files. Here it is. And yes, it's an exercise to learn how to use fstream classes.
// // TABEXP.CPP //
#include #include
// self-explanatory const unsigned short DEFAULT_TABSIZE = 4;
int main (int NArg, char *const arg[]) {
// help if invalid syntax is used if (NArg < 3) { cout << "\nTABEXP - Tab Expander" << "\nUsage:" << "\n" << "\n " << arg[0] << " infile outfile [tabsize]" << "\n" << "\nTab Expander expands all TABs in infile to spaces in outfile" << "\ninfile must be a text file, default tabsize is " << DEFAULT_TABSIZE << "\nWARNING: data loss MAY occur; if you lose data, I'm sorry :)" << "\n"; } else { // correct syntax used
// open input file ifstream inFile(arg[1]);
// error if (!inFile.good()) { cout << "\nSorry cannot open input file " << arg[1] << " - Exiting...\n"; return 1; }
// open output file, cannot be overwritten (only at the moment...) ofstream outFile(arg[2], ios::out|ios::noreplace);
// error if (!outFile.good()) { cout << "\nSorry cannot open output file " << arg[2] << " - Exiting...\n"; return 1; }
// obvious unsigned short tabSize = 0;
// tabSize is non-zero if third parameter exists and is valid if (NArg > 3) tabSize = atoi (arg[3]);
// decide wether to use default value if (tabSize == 0) tabSize = DEFAULT_TABSIZE;
// print some info on the console cout << "\nUsing tabsize = " << tabSize; cout << "\nWorking... ";
// ch is used for input and output; slow but it works well char ch;
// a counter int i;
// read char as long as it is not at EOF // if it's a tab, then write 'tabSize' spaces in output // if it's not, then copy in in output while (!inFile.get(ch).eof()) { if (ch == '\t') { for (i=0; i < tabSize; i++) { outFile.put(' '); } } else { outFile.put(ch); } }
// politely close input file and *safely* close output file inFile. close(); outFile.close();
// if you don't see this, start worrying... cout << "operation completed.\n";
}
// return 'no-error' errorlevel return 0;
}
|