Streaming and I/0 Chapter 14 D&D. Menu Reading/writing text file streams Reading/writing string streams Command line arguments.

Slides:



Advertisements
Similar presentations
Graohics CSC 171 FALL 2001 LECTURE 16. History: COBOL Conference on Data System Languages (CODASYL) - led by Joe Wegstein of NBS developed the.
Advertisements

CMSC 2021 C++ I/O and Other Topics. CMSC 2022 Using C++ Stream I/O Default input stream is called cin Default output stream is called cout Use the extraction.
File Input/Output. External Files Batch –Requires use of data files (save to disk) –Batch can be run during off peak use –allows things to be complete.
CS 1620 File I/O. So far this semester all input has been from keyboard all output has been to computer screen these are just two examples of where to.
1 Text File I/O Chapter 6 Pages File I/O in an Object-Oriented Language Compare to File I/O in C. Instantiate an ofstream object. Like opening.
Chapter 7: Files Mr. Dave Clausen La Cañada High School.
File streams Chapter , ,
1 DOS vs. UNIX files Ending lines with “\r\n” vs. “\n” Reading an entire line at a time getline() To skip white space or not cin >> ch; vs. ch = cin.get();
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
Basic Elements of C++ Chapter 2.
Darbas su failais Arnas Terekas IT 1gr. Vilniaus universitetas Matematikos ir informatikos fakultetas.
STREAMS AND FILES OVERVIEW.  Many programs are "data processing" applications  Read the input data  Perform sequence of operations on this data  Write.
Fundamental Programming Command Line Parameters and File I/O.
Ch 10. Input/Output1 Ch. 10 Input/Output Oregon State University Timothy Budd.
ITEC 320 C++ Examples.
1 Operating Systems Lecture 2 UNIX and Shell Scripts.
File I/O ifstreams and ofstreams Sections 11.1 &
Chapter 9 I/O Streams and Data Files
1 CS161 Introduction to Computer Science Topic #13.
Topics 1.File Basics 2.Output Formatting 3.Passing File Stream Objects to Functions 4.More Detailed Error Testing 5.Member Functions for Reading and 6.Writing.
Advanced File Operations Chapter File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to.
File Input and Output in C++. Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) Keyboard Screen executing program input data.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
File IO and command line input CSE 2451 Rong Shi.
CSE 232: C++ debugging in Visual Studio and emacs C++ Debugging (in Visual Studio and emacs) We’ve looked at programs from a text-based mode –Shell commands.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
File I/O in C++ II. Open() function Open() is a member function in each classes ( fstream, ifstream, ofstream) Void fstream :: open ( const char *filename,
CSE 332: C++ IO We’ve Looked at Basic Input and Output Already How to move data into and out of a program –Using argc and argv to pass command line args.
Vectors One-Dimensional Containers. Problem A file contains a sequence of names and scores: Ann92 Bob84 Chris89... Using OCD, design and implement a program.
Streams, and File I/O Review. STREAMS Review STREAMS Streams are sequences of bytes. C++ I/0 occurs in streams Input – bytes flow from device to memory.
Chapter -7 Basic function of Input/output system basics and file processing Stream classes : I/O Streams. A stream is a source or destination for collection.
Cryptography.
Chapter 11 Standard C++ Strings and File I/O Dept of Computer Engineering Khon Kaen University.
C++ REVIEW INPUT/OUTPUT (I/O). BRIEF NOTE “CLASSES” AND “STRUCTS” AND “TYPES” They are ADTs… They define data and operations on that data The ADTs in.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
Learners Support Publications Working with Files.
CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file?
Lecture 14 Arguments, Classes and Files. Arguments.
Std Library of C++ Part 2. vector vector is a collection of objects of a single type vector is a collection of objects of a single type Each object in.
24 4/11/98 CSE 143 Stream I/O [Appendix C]. 25 4/11/98 Input/Output Concepts  Concepts should be review!  New syntax, but same fundamental concepts.
File I/O in C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
File I/O in C++ I. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide.
Chapter Expressions and Interactivity 3. The cin Object 3.1.
Advanced File Operations Chapter File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to.
File I/O. Files allow permanent storage of programs and data. ifstream and ofstream objects –For file I/O the inclusion of is required. –Objects for file.
CS 1430: Programming in C++ 1. File Input in VS Project Properties Debugging Command Arguments quiz8-1.out We want to know how to do it ourselves, right?
Module 5: I/O and Strings #1 2000/01Scientific Computing in OOCourse code 3C59 Module 5: I/O and STRINGS In this module we will cover The C++ input and.
CSE 232: Moving Data Within a C++ Program Moving Data Within a C++ Program Input –Getting data from the command line (we’ve looked at this) –Getting data.
Chapter 4: Introduction To C++ (Part 3). The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Information.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3: Expressions and Interactivity.
Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 Pass-by-Value - default passing mechanism except.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Chapter Eight: Streams Slides by Evan Gallagher.
Chapter Topics The Basics of a C++ Program Data Types
MT262A Review.
Basic Elements of C++.
Copyright © 2003 Pearson Education, Inc.
Basic Elements of C++ Chapter 2.
RANDOM NUMBER GENERATOR & STREAMS (FILE I/O, STRING)
Chapter 13: Advanced File and I/O Operations
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Topics Input and Output Streams More Detailed Error Testing
Standard Input/Output Stream
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
CS150 Introduction to Computer Science 1
File I/O in C++ I.
CS150 Introduction to Computer Science 1
File I/O.
CHAPTER 4 File Processing.
File I/O in C++ I.
Presentation transcript:

Streaming and I/0 Chapter 14 D&D

Menu Reading/writing text file streams Reading/writing string streams Command line arguments

Reading/writing text streams All programs we’ve written so far have read input from standard input, and written output to standard output. cin, cout, and cerr are C++ streams. We will now extend this concept to disk files.

To access a disk file, we can open a file stream variable. #include ifstreaminfile(“filename”); // input ofstream outfile(“filename”); // output fstream inoutfile(“filename”); // in/output

Example (code fragment): #include... ifstream input_data; input_data.open(“myfile”); int n; double x; input_data >> n >> x;...

Reading strings from streams (code fragment): #include... ifstream input_data; input_data.open(“myfile”); string s; input_data >> s; // read word getline(input_data,s);...

Reading characters from streams (code fragment): #include... ifstream input_data; input_data.open(“myfile”); char ch; input_data.get(ch); // get one character...

Some other member functions of input streams: input_stream.peek(ch); // look ahead one char input_stream.unget(); // put the last char back Some member functions common to both input and output streams: input_stream.fail(); // stream op failed input_stream.eof(); // end of stream reached input_stream.close(); input_stream.open(“filename”);

Code fragment: char ch; ifstream input_stream; input_stream.open(“mydata”); input_stream.get(ch); // get one character if(‘0’<= ch and ch <= ‘9’) { input_stream.unget(); int n; input_stream >> n; } input_stream.close();

Output file streams (code fragment): #include... ofstream output_data(“myfile”); output_data << n << “_” << x << “\n”; output_data.put(ch); // write a single character output_data.close();...

Many compilers do not support string parameters to the open/close file function.... string s = “myfile”; ofstream output_data; output_data.open(s); // sometimes supported... output_data.open(s.c_str());... member function s.c_str() yields standard C character array

Example paths as strings in Unix:... string s = “/home/ugrad/hacker/myfile.dat”; s = “~hacker/myfile.dat”; // file in home directory s = “myfile.dat” // file in current directory On PC: string s = “C:\\hacker\\myfile.dat”; // corresponds with file C:\hacker\myfile.dat

File paths User could be prompted for a file name cout << “Type filename”; cin >> s; File name could be computed or concatenated: string homedir = “~”; s = homedir + “myfile” + “dat”;

String Streams #include istringstream: reads from a string ostringstream: writes to a string Has same interfaces as other stream classes, but allows read/write to a string object.

Code fragment:... string input = “January 23, 1955”; istringstream instr(input); // constructor string month,comma; int day,year; instr >> month >> day >> comma >> year;... C++ does the conversion from string to the other types.

#include int string_to_int(string s) { istringstream instr(s); // constructor int n; instr >> n; return n; }

#include string double_to_string(double a) { ostringstream outstr; // constructor outstr << a; return outstr.str(); // return string equiv. }

#include string double_to_string(double a) { ostringstream outstr; // constructor outstr << setprecision(5); // 5 places after decimal outstr << a; return outstr.str(); // return string equiv. } // double_to_string(sqrt(2)) returns “ ”;

Command Line Arguments There are different ways to start a program: –click on icon –type name of program and return the latter is called invoking the program from the command line.

Command Line Arguments You can include additional arguments on the command line; e.g., in Unix: ls -l make main g++ -Wall -ansi main.cpp -o main Usually, we interpret symbols preceded by - as options.

Arguments to C++ main function int main(int argc, char *argv[]) {... }

Example command line: myprog -v input.dat In this case argc == 3 string(argv[0]) == “myprog” string(argv[1]) == “-v” string(argv[2]) == “input.dat” argv[0] always gives the name of the program argc always >= 1

Number of command line arguments can vary: myprog -v input.dat myprog myprog -i -v input.dat -o output.dat argv[0] always gives the name of the program argc always >= 1 What is the value of argc in each of the cases above??

Caesar’s Encryption Algorithm Also known as Caesar’s Cipher. Scrample message via algorithm: –specify integer key k between 0 and 25 –to encrypt, shift each input character by k Example: k = 3, input = “ABCDEFG” output = “DEFGHIJ” To decrypt message, use key = -k

Program arguments optional -d flag indicates decryption rather than encryption optional encryption key -k input file name output file name Examples: crypt -k11 input.txt encrypt.txt crypt -d -k11 encrypt.txt output.txt

functions used usage(string program_name); open_file_error(string filename); remainder(int a, int n); encrypt(char ch, int k); encrypt_file(ifstream& in, ofstream& out, int k) string_to_int(string s); main(int argc, char *argv);

Main if argc 5 usage(string(argv[0])); exit; for all command line arguments if -d option, then set decrypt if -kn option, set key=n, otherwise key=3 if not option, input filename or output filename openfile (either infile or outfile) if(nfile != 2) usage(string(argv[0])); exit; if(decrypt) key = -key; encrypt_file(infile,outfile,key); infile.close(); outfile.close(); done;

void usage(string program_name) /* PURPOSE: Prints usage instructions RECEIVES: program_name - the name of this program */ { cout << "Usage: " << program_name << " [-d] [-kn] infile outfile\n"; exit(1); }

void open_file_error(string filename) /* PURPOSE: Prints file opening error message RECEIVES: filename - the name of the file that could not be opened */ { cout << "Error opening file " << filename << "\n"; exit(1); }

void encrypt_file(ifstream& in, ofstream& out, int k) /* PURPOSE: Encrypt a file using the Caesar cipher RECEIVES: in - the file to read from out- the file to write to k - the encryption key */ { char ch; while (in.get(ch)) out.put(encrypt(ch, k)); }

char encrypt(char ch, int k) /* PURPOSE: Encrypt a character using the Caesar cipher RECEIVES: ch - the character to encrypt k - the encryption key RETURNS: the encrypted character */ { const int NLETTER = 26; if ('A' <= ch && ch <= 'Z') return static_cast ('A' + remainder(ch - 'A' + k, NLETTER)); if ('a' <= ch && ch <= 'z') return static_cast ('a' + remainder(ch - 'a' + k, NLETTER)); return ch; }

int remainder(int a, int n) /* PURPOSE: Compute correct remainder for negative dividend RECEIVES: a - an integer n - an integer > 0 RETURNS: the mathematically correct remainder r such that a - r is divisible by n and 0 <= r and r < n */ { if (a >= 0) return a % n; else return n (-a - 1) % n; }

int string_to_int(string s) /* PURPOSE: Convert a string to an integer, e.g. "3" -> 3 RECEIVES: s - a string representing an integer RETURNS: the equivalent integer */ { istringstream instr(s); int n; instr >> n; return n; }

int main(int argc, char* argv[]) { bool decrypt = false; int key = 3; int nfile = 0; /* the number of files specified */ ifstream infile; ofstream outfile; if (argc 5) usage(string(argv[0]));

for (int i = 1; i < argc; i++) { string arg = string(argv[i]); if (arg.length() >= 2 and arg[0] == '-') /* it is a command line option */ { char option = arg[1]; if (option == 'd') decrypt = true; else if (option == 'k') key = string_to_int(arg.substr(2, arg.length() - 2)); }

else { nfile++; if (nfile == 1) { infile.open(arg.c_str()); if (infile.fail()) open_file_error(arg); } else if (nfile == 2) { outfile.open(arg.c_str()); if (outfile.fail()) open_file_error(arg); }

if(nfile != 2) usage(string(argv[0])); if (decrypt) key = -key; encrypt_file(infile, outfile, key); infile.close(); outfile.close(); return 0; } // end of main