Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @file p2.cpp
- *
- * CS 150 - Command Line Arguments and Binary Files
- */
- /*
- 1. No arguments supplied? Print an error message on standard error and exit
- 2. One argument? Open the input file in binary mode and print (on the console)
- the name of the file followed by its size in bytes. See format below.
- • Cannot open file? Print error message (standard error) and exit
- 3. Two arguments? Open the second file for output (in text mode) and the
- information from the first file in this file instead of to the screen.
- • Cannot open file for output? Print error message (standard error) and exit
- */
- #include <iostream>
- #include <fstream>
- #include <sstream>
- #include <string>
- #include <cstdlib>
- using namespace std;
- //////// FUNCTION PROTOTYPES
- bool printBinarySize(char * filename, ostream& out);
- ////////////////////////////
- //////////////////////////// DEFINE YOUR MAIN FUNCTION BELOW THIS LINE
- int main(int argc, char * argv[])
- {
- switch (argc)
- {
- case 1:
- cerr << "Usage: p2 file-to-open [file-to-save-to]" << endl;
- return 1;
- break;
- case 2:
- if (! printBinarySize(argv[1], cout)) // it still executes
- return 1;
- break;
- case 3:
- ofstream out(argv[2]);
- if (out.fail())
- {
- cerr << "Cannot open the output file " << argv[2] << " for writing.";
- return 1;
- }
- if (! printBinarySize(argv[1], out)) // it still executes
- return 1;
- break;
- }
- return 0;
- }
- ////////////// FUNCTIONS
- /*
- Function that opens a binary file, checks if it could be open,
- gets its size in bytes, and then send the size to an ostream
- object.
- Returns false if it could not open the file and true if succeded.
- */
- bool printBinarySize(char * filename, ostream& out)
- {
- ifstream in(filename, ios::binary | ios::in | ios::ate); //open to read and at the end
- if (in.fail())
- {
- cerr << "Cannot open the input file " << filename;
- return false;
- }
- ios::pos_type size = in.tellg(); // get posicion ATE (At The End)
- out << filename << ": size is " << size << " bytes.";
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement