Lecture 2OutlineMore UNIX Commands 1More UNIX Commands 2Handling Invalid Input 1Handling Invalid Input 2Command-line Argumentsargc, argvFile StreamsOpening File Streams 1Opening File Streams 2Using File StreamsReading from a FileReading Whitespace 1Reading Whitespace 2Closing FilesHomework 1Friday, August 27 CS 215 Fundamentals of Programming II - Lecture 2 1Lecture 2Has everyone logged into Linux?Has everyone successfully compiled and run a program on Linux?Did everyone complete the in-class exercise from Wednesday?Today's homework assignment is due by class time on Monday, when the submission system will be demonstrated.Friday, August 27 CS 215 Fundamentals of Programming II - Lecture 2 2OutlineMore UNIX commandsHandling invalid inputCommand-line argumentsFile streamsFriday, August 27 CS 215 Fundamentals of Programming II - Lecture 2 3More UNIX CommandsCopying files on local machinecp <file to be copied> <new name or directory>If a new name, a copy in current directoryIf a directory, a copy with same nameExample: cp /home/hwang/cs215/lecture02/*.* .Friday, August 27 CS 215 Fundamentals of Programming II - Lecture 2 4More UNIX CommandsCopying files on remote machinescp - same syntax as cpRemote name is prefixed with "remotehost:" if username is the same or "username@remotehost:" if username is not the sameNames relative to remote user home directoryExample to copy from remote to local:scp [email protected]:/home/hwang/cs215/lecture02/*.* .Example to copy from local to remote:scp file.cpp [email protected]:cs215/lecture02Friday, August 27 CS 215 Fundamentals of Programming II - Lecture 2 5Handling Invalid InputWhen an I/O stream is used in a boolean context, it converts to true when the stream is valid and false when the stream is invalid.Example: checking for bad user inputcin >> anInt;if (!cin) { cout << "Input error" << endl;}Can combine this into one step:if (!(cin >> anInt)) { cout << "Input error" << endl; }Friday, August 27 CS 215 Fundamentals of Programming II - Lecture 2 6Handling Invalid InputAfter invalid input has been detected, stream must be cleared and offending input removed from the stream. (Program in input.cpp) bool valid; int value; string errorInput;do { cout << "Enter an integer: "; if (cin >> value) { valid = true; } else { valid = false; cin.clear(); // reset the stream getline (cin, errorInput); // skip bad data cout << "Bad input\n"; }} while (!valid);cout << "Entered value: " << value << endl;Friday, August 27 CS 215 Fundamentals of Programming II - Lecture 2 7Command-line ArgumentsMost UNIX programs are not interactiveE.g. file names are given on command line and are called command-line argumentsIn C++ (and C), they are accessed using the following function header for main:int main (int argc, char *argv[])Parameter names are conventionalFriday, August 27 CS 215 Fundamentals of Programming II - Lecture 2 8argc, argvargc is the number of "words" on the command line, including the command itself. argc would be 4 for the following exampleg++ -o hello hello.cppargv is an array C-strings that are the words. Note that the command word is argv[0], so the first argument is argv[1] and the last one is argv[argc-1].Always check if argc is the correct number.Friday, August 27 CS 215 Fundamentals of Programming II - Lecture 2 9File StreamsThe main reason for using command-line arguments is to pass names of files to programs rather than ask for them interactively.File streams are objects connected to files.Two types are defined in system library <fstream>:ifstream inFileStream; // input file streamofstream outFileStream; // output file streamFriday, August 27 CS 215 Fundamentals of Programming II - Lecture 2 10Opening File StreamsNames of files must be C-strings (not C++ strings), like argv elementsAttach physical file when variable is declared (called explicit-value construction)ifstream inFileStream(argv[1]);ofstream outFileStream(argv[2]);Use open( ) member function (i.e., a function attached to the file stream object)inFileStream.open(argv[1]);outFileStream.open(argv[2]);Friday, August 27 CS 215 Fundamentals of Programming II - Lecture 2 11Opening File StreamsShould always check if file open was successful.ifstream inFileStream(argv[1]);if (!inFileStream) { // invalid stream cerr << "Error opening file: " << argv[1] << endl; exit(1);}exit() is defined in <cstdlib>Friday, August 27 CS 215 Fundamentals of Programming II - Lecture 2 12Using File StreamsFile streams are a kind of I/O streamInsertion operator (<<) is used with ofstreams to write to a file.Extraction operator (>>) is used with ifstreams to read from a fileFriday, August 27 CS 215 Fundamentals of Programming II - Lecture 2 13Reading from a FileWhen an attempt is made to read past the end of a file, the file stream becomes invalid. The general pattern for reading from a file is:// Open input fileifstream inFileStream (argv[1]);if (!inFileStream) { // error msg and exit }// Read from fileitem_type value; while (inFileStream >> value) { // do something with value}Friday, August 27 CS 215 Fundamentals of Programming II - Lecture 2 14Reading WhitespaceProgram firstcopy.cpp attempts to implement the cp UNIX command to copy a file by copying one character at a timeCompile, run, and test$ g++ -o firstcopy firstcopy.cpp$ ./firstcopy test1.dat copytest1.dat$ diff test1.dat copytest1.datUNIX command: diff - compare two files character by character; no output if the sameFriday, August 27 CS 215 Fundamentals of Programming II - Lecture 2 15Reading WhitespaceTry again$ ./firstcopy test2.dat copytest2.dat$ diff test2.dat copytest2.dat Problem: insertion operator (>>) skips whitespaceUse get( ) member function. It takes a character argument that is filled with the read character. It also returns false if the stream fails.while (in.get(ch))Friday, August 27 CS 215 Fundamentals of Programming II - Lecture 2 16Closing FilesClose files using close( ) member functioninFileStream.close();outFileStream.close();Friday, August 27 CS 215 Fundamentals of Programming II - Lecture 2 17Homework 1Assignment is posted to course webpageDue on Monday at beginning of classcipher.cpp should be on the computer you will be using in class. I.e., on csserver or your own laptopIt will be submitted electronically during
View Full Document