Write a complete C++ program that satisfies the following requirements:
it accepts two command line arguments if too few arguments are provided the program displays an error message and exits otherwise the first argument is treated as the name of an input file, the second argument is treated as an integer value, referred to as N below the program attempts to open the file for reading if the open succeeds it reads the first N characters from the file, displaying them on the screen (ALL characters count) once N characters have been displayed or the end of the file is reached the program should close the file and exit
Sample solution #include <iostream> #include <fstream> using namespace std; int main(int argc, char *argv[]) { // check valid number of arguments was provided if (argc < 3) { cout << "Correct usage is \n"; cout << argv[0] << " filename numchars\n"; return 0; } // try opening the file ifstream fpin; fpin.open(argv[1]); if (fpin.fail()) { cout << "Unable to open file " << argv[1] << endl; return 0; } // display the first N characters int N = atoi(argv[2]); cout << "The first " << N << " characters of file "; cout << argv[1] << " are:\n"; int count = 0; while ((count < N) && (!fpin.eof())) { char c; fpin.get(c); if (!fpin.eof()) { count++; cout << c; } } fpin.close(); cout << endl; } |