write a program that can print out the first n lines of a text file. Can you do that yet?
write a main() function that can get the user parameters from the command line, Can you do that yet?
When you can do those two things, your overall task will appear simple.
Lets loan from your other thread: void read_numbers( ifstream& f, vector<double>& numbers );
Not a verbatim loan, but part of the idea: void show_head( std::ifstream& f, size_t count );
What should it do? It gets an open stream and a number.
It should read at most count lines and print them.
Could you write the implementation for such function?
It's a good idea to use argv[0] for the program name in the usage function. That way the user can rename the program and it will still make sense:
[code]int main(int argc, char* argv[])
{
usage(argv[0]);
return 0;
}
No, it is not. The getopt() is not part of C++ standard. You should be able to find its description from the net.
The Boost libraries do have C++ code for managing options, i.e. an alternative for getopt(), but Boost has to be installed separately. Some bits of Boost have already been copied into the C++ standard.
However, you are doing homework and I bet that the purpose of this one is to learn about argc and argv and more importantly to practice creating a logical set of tests that cover all the possibilities.
int opt;
unsigned numLines = 10; // number of lines to print. 10 is default
while ((opt = getopt(argc, argv, "n:") != EOF) {
switch (opt) {
case'n':
numLines = atoi(optarg);
if (numLines < 1) {
usage(argv[0]); // bad argument to -n
// You need to add more error checking here for things like "-n42bleh"
}
break;
default:
usage(argv[0]); // unknown option
}
}
// optind is now the index of file argument
if (optind >= argc) usage(argv[0]); // no file given
for (unsigned i=optind; i< argc; ++i) {
head(argv[i]);
}
return 0;
What if you have a file named "-myfile"? How can the program tell that from a bad command line argument. Worse still, what if you have a file named "-n33"?? How can it know to process that as a file and not as "-n 33"?? What if you want to print the first 88 lines of a file called -n88???
Getopt actually handles all of these cases. You can force the option processing to stop by entering "--": getopt -n88 -- -n88 // Print the first 88 lines of file "-n88"
This is why you really want to use getopt().
You can probably call available functions, and hopefully getopt() is one of them. In the unix world, getopt() is used pretty universally for command line parsing, which makes command interfaces very consistent.
If you can't use getopt() then you'll have to write your own code to parse the command line. The various things to check for are:
- no option after "-n"
- invalid option after "-n", including something that starts with digits, or a negative number
- invalid option (e.g., -a)
- No file specified.