C++ Command Line Arguments and File I/O
Work on program 4
Lab 8
CSCI 112
Goals:
Introduce the how command line
arguments are read in C++.
Introduce file input/output in C++.
Assignment 5 will require that you use both of these mechanisms.
mycat.cpp
is a program that reads all the lines in a file and dumps them to
standard
output. It illustrates how C++ reads arguments from the command
line and how C++ performs file I/O.
Now I will go over mycat.cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int
main(int argc, char *argv[])
{
// make sure a filename was specified on the command line
if (argc == 1)
{
// write to standar error (cerr)
cerr << "no filename specified" << endl;
return 1; // 1 is error condition
}
if (argc > 2)
{
cerr << "too many arguments specified on the command line" << endl;
return 1;
}
// open the files specified in argv[1]. The "ios::in" opens the file in read mode.
ifstream my_ifile(argv[1], ios::in);
// if could not open file
if (!my_ifile)
{
cerr << "could not open file <" << argv[1] << ">" << endl;
return 1; // error
}
// buffer to hold input line
string buffer;
// getline returns 0 (false) at end of file (when it cannot read another line)
while (getline(my_ifile, buffer, '\n') != false)
{
// write the line to standard output
cout << buffer << endl;
}
return 0; // everything is ok
}
Exercise 1:
Rewrite mycat.cpp so that it
writes all the command line arguments to standard output. Call it
args.cpp. For example:
$ g++ -o args args.cpp
$ args one two three
one
two
three
$
Exercise 2:
Rewrite mycat.cpp so that it takes
three command line arguments:
1)
an integer (call it reps)
2) a filename to be used as the input file
3) a filename to be used as the output file
The program should read from the specified input file, and write each
line reps time to the output file. For example, given the
following input:
$ mycat 3 data1 data2
Your program should read each line in data1 and write it 3 times
in data2.
You will need to convert the string "3" to an integer. Use the
function atoi() (ascii-to-integer).
Use the following when opening a file for writing:
ofstream
my_ofile(filename, ios::out);
Program 5 requires three command line arguments (an integer, an input
filename, an output filename) so completing this exercise will help you
with program 5. Make sure you keep your solution so you can use
it for program 5.
Exercise 3:
Work on program 4