#include #include #include int main(int argc, char* argv[]) { if ( argc <= 1 ) { std::cout << "Usage: toc filename\n"; return 0; } std::ifstream file( argv[1] ); if ( ! file ) { std::cerr << "toc: could not open " << argv[1] << std::endl; return 1; } size_t max_len_title = 0; size_t max_len_page = 0; // Traverse the file for first time to calculate max lengths std::string line; while ( std::getline(file, line) ) { size_t pos = line.rfind('\t'); if ( pos != std::string::npos ) { max_len_title = std::max( max_len_title, pos); max_len_page = std::max( max_len_page, line.length() - pos - 1 ); } } // Rewind cursor to the beginning of the file file.clear(); // clear EOF flag file.seekg(0, std::ios_base::beg); // Traverse the file for second time to print the table of contents using formatted ouput while ( std::getline(file, line) ) { size_t pos = line.rfind('\t'); if ( pos != std::string::npos ) { std::cout << std::setfill('.') << std::left << std::setw(max_len_title) << line.substr(0, pos); std::cout << std::setfill(' ') << std::right << std::setw(max_len_page) << line.substr(pos + 1) << std::endl; } } file.close(); return 0; }