// head.cc g++ -g -o head head.cc // example of command line arguments in C++ and named files // Usage: head -20 file1 file2 ... // This would output the first 20 lines of each file // Default number of lines is 10. #include // named files #include // atoi() #include #include using namespace std; int main( int argc, char* argv[] ) { int nlines = 10; for( int i = 1; i < argc; i++ ) if ( *argv[i] == '-' ) nlines = atoi( argv[i]+1 ); // skip over '-' sign else { ifstream in( argv[i] ); // try to open the file if ( ! in ) cerr << "Unable to open: " << argv[i] << endl; else { cout << "==> " << argv[i] << " <==\n"; string line; // used as buffer for( int j = 0 ; j < nlines && getline( in, line, '\n' ); j++ ) cout << line << endl; } } }