// Source: "Software Design ...", John A Robinson, Newnes, 2004, page 170. // // Add line numbers to a source code listing // Prepend to each line a string: ' ',linenum in fixed width,": " // To decide width of field, have to count the number of lines // // John Robinson 7 September 2003 #include #include #include using namespace std; int main(int argc, char *argv[]) { char linebuffer[2048]; if (argc != 3) { cerr << "Usage: addnumbers in_codefile out_numbfile\n"; return -1; } ifstream infile(argv[1]); if (!infile) { cerr << "Can't open " << argv[1] << endl; return -1; } // Count lines in infile int numlines = 0; while(!infile.eof()) { infile.getline(linebuffer, 2048); numlines++; } numlines--; // Because last one was eof infile.clear(); // Clear eof flag infile.seekg(0); // Rewind to start of infile // Work out field width for linenumbers int fieldwidth = 0; while (numlines) { fieldwidth++; numlines /= 10; } ofstream outfile(argv[2]); if (!outfile) { cerr << "Can't open " << argv[2] << endl; return -1; } int linenumber = 0; while(1) { // Until we break out by finding end of file infile.getline(linebuffer, 2048); if (infile.eof()) break; linenumber++; outfile << ' ' << setw(fieldwidth) << linenumber << ": "; outfile << linebuffer << endl; } infile.close(); outfile.close(); return 0; }