Unformatted text preview:

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 2Has 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 2OutlineMore UNIX commandsHandling invalid inputCommand-line argumentsFile streamsFriday, August 27 CS 215 Fundamentals of Programming II - Lecture 2 3More UNIX CommandsCopying files on local machinecp <file to be copied> <new name or directory>If a new name, a copy in current directoryIf a directory, a copy with same nameExample: cp /home/hwang/cs215/lecture02/*.* .Friday, August 27 CS 215 Fundamentals of Programming II - Lecture 2 4More UNIX CommandsCopying files on remote machinescp - same syntax as cpRemote name is prefixed with "remotehost:" if username is the same or "username@remotehost:" if username is not the sameNames relative to remote user home directoryExample 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 InputWhen 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 InputAfter 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 ArgumentsMost UNIX programs are not interactiveE.g. file names are given on command line and are called command-line argumentsIn 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, argvargc is the number of "words" on the command line, including the command itself. argc would be 4 for the following exampleg++ -o hello hello.cppargv 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 StreamsThe 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 StreamsNames of files must be C-strings (not C++ strings), like argv elementsAttach 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 StreamsShould 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 StreamsFile streams are a kind of I/O streamInsertion 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 FileWhen 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 WhitespaceProgram firstcopy.cpp attempts to implement the cp UNIX command to copy a file by copying one character at a timeCompile, run, and test$ g++ -o firstcopy firstcopy.cpp$ ./firstcopy test1.dat copytest1.dat$ diff test1.dat copytest1.datUNIX command: diff - compare two files character by character; no output if the sameFriday, August 27 CS 215 Fundamentals of Programming II - Lecture 2 15Reading WhitespaceTry again$ ./firstcopy test2.dat copytest2.dat$ diff test2.dat copytest2.dat Problem: insertion operator (>>) skips whitespaceUse 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 FilesClose files using close( ) member functioninFileStream.close();outFileStream.close();Friday, August 27 CS 215 Fundamentals of Programming II - Lecture 2 17Homework 1Assignment is posted to course webpageDue on Monday at beginning of classcipher.cpp should be on the computer you will be using in class. I.e., on csserver or your own laptopIt will be submitted electronically during


View Full Document

UE CS 215 - LECTURE NOTES

Documents in this Course
Lecture 4

Lecture 4

14 pages

Lecture 5

Lecture 5

18 pages

Lecture 6

Lecture 6

17 pages

Lecture 7

Lecture 7

28 pages

Lecture 1

Lecture 1

16 pages

Lecture 5

Lecture 5

15 pages

Lecture 7

Lecture 7

28 pages

Load more
Download LECTURE NOTES
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view LECTURE NOTES and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view LECTURE NOTES 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?