CSCI 1200 - Spring 2007 Computer Science II |
|
Home Contact Information
Course Overview
Schedule
Calendar
Textbooks
Homework
C++ Development
|
Command Line ArgumentsIn order for your program to receive arguments from the command line, you will make use of the optional arguments to the main function. Here is the prototype:int main(int argc, char* argv[])The parameter argc contains the number of strings on the command line (including the executable name). And the array argv stores those c-style strings. You can access the executable name with argv[0] and the arguments with argv[1], argv[2], etc. Reading From & Writing To Filesstd::cin & std::cout are used to read data from and write data to the "console". Often we would rather read data from a file and/or write the output to a file. We can do this using the fstream library:#include <fstream>Here's an example fragment of code that attempts to open an input file stream for a file name specified on the command line: std::ifstream in_str(argv[1]);It is good coding practice to verify that the input stream was successfully opened: if (!in_str) { std::cerr << "Can't open " << argv[1] << " to read.\n"; exit(1); }Likewise here's how to open a stream for output: std::ofstream out_str(argv[2]); if (!out_str) { std::cerr << "Can't open " << argv[2] << " to write.\n"; exit(1); }Once the streams are created, you can use in_str & out_str just like you use std::cin & std::cout. Redirecting Input & OutputWhat if you have an interactive program that uses std::cin & std::cout to read from and write to the "console", but you'd like to take the input from a file and you'd rather not rewrite the program to use the input & output streams described above. For example if you're debugging & testing an interactive program you'd rather not repeatedly type in the same test cases. Asking the executable to read from a file instead of the console and/or write to a file instead of the console is called file redirection.With Cygwin/Linux/FreeBSD/UNIX, at the command prompt simply type: program.exe < input.txt > output.txtWith Visual Studio:
Note: Once you've sent your output to a file, you can quickly compare it to another file (the provided sample output) using the UNIX utility diff (available on Cygwin): diff my_output.txt sample_output.txt WinDiff is another option for Windows users. Please see a TA or the instructor in office hours if you have a question about these programs. |