C
Christopher Benson-Manica
This is intended to be a simple version of the Unix "head" command,
i.e. a utility that displays the first n lines of a file. Comments
welcomed...
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main( int argc, char *argv[] )
{
if( argc < 2 || argc > 3 ) {
// endl preferable to "\n" here?
cerr << "Usage: " << argv[0] << " <file> [lines]" << endl;
return EXIT_FAILURE;
}
ifstream f( argv[1] );
unsigned int count;
if( argc == 3 ) {
// as suggested in responses to my question about atoi()
(stringstream(argv[2])) >> count; // no error checking!
}
else {
count=10;
}
if( !f ) {
// endl preferable to "\n" here?
cerr << "Could not open file: " << argv[1] << endl;
return EXIT_FAILURE;
}
string s;
while( !f.eof() && count-- ) {
getline( f, s );
// "\n" preferable?
cout << s << "\n";
}
f.close();
return EXIT_SUCCESS;
}
i.e. a utility that displays the first n lines of a file. Comments
welcomed...
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main( int argc, char *argv[] )
{
if( argc < 2 || argc > 3 ) {
// endl preferable to "\n" here?
cerr << "Usage: " << argv[0] << " <file> [lines]" << endl;
return EXIT_FAILURE;
}
ifstream f( argv[1] );
unsigned int count;
if( argc == 3 ) {
// as suggested in responses to my question about atoi()
(stringstream(argv[2])) >> count; // no error checking!
}
else {
count=10;
}
if( !f ) {
// endl preferable to "\n" here?
cerr << "Could not open file: " << argv[1] << endl;
return EXIT_FAILURE;
}
string s;
while( !f.eof() && count-- ) {
getline( f, s );
// "\n" preferable?
cout << s << "\n";
}
f.close();
return EXIT_SUCCESS;
}