CSC 107 – Programming For Science. Today’s Goal  Get familiar with opening & closing files  Declaring variables for use with files  Using variables.

Slides:



Advertisements
Similar presentations
CSC 107 – Programming For Science. Final Exam Thurs., Dec. 10 th from 8AM – 10AM in OM 221 For exam, plan on using full 2 hours If major problem, come.
Advertisements

CSC 107 – Programming For Science. Final Exam  Fri., Dec. 14 th from 12:30PM – 2:30PM in SH1028  For exam, plan on using full 2 hours  If major problem,
CSC 107 – Programming For Science. Today’s Goal  Get familiar with multi-dimensional arrays  Creating variables for multi-dimensional array  Multi-dimensional.
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 10.
1 11/3/08CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
1 Programming with Data Files Chapter 4 2 Standard Input Output C++ Program Keyboard input cin Output Screen cout.
Chapter 5: Loops and Files.
1 10/29/07CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
C++ plus. 2 Goals Some general C++ tips 3 C++ Tips is header file for a library that defines three stream objects Keyboard an istream object named cin.
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
CSC 107 – Programming For Science. Today’s Goal  Learn how arrays normally used in real programs  Why a function returning an array causes bugs  How.
CSC 107 – Programming For Science. Today’s Goal ALL  Understand why ALL I/O is file I/O  Common bugs to avoid when coding with files in C++  Get a.
CSC 107 – Programming For Science. Announcements  Tutors available MTWR in WTC206/WTC208  Special lab (with Macs) & not in the Tutoring Center  Can.
STREAMS AND FILES OVERVIEW.  Many programs are "data processing" applications  Read the input data  Perform sequence of operations on this data  Write.
CSC 213 – Large Scale Programming. Project #1 Recap.
1 CS 101 Lecture 2. 2 Input from the Keyboard Here is a program to accept input from the keyboard and put into into two variables. #include main(){ cout.
CSC 107 – Programming For Science. Announcements  Memorization is not important, but…  … you will all still be responsible for information  Instead.
CSC 107 – Programming For Science. Today’s Goal  Get familiar with opening & closing files  Declaring variables for use with files  Using variables.
CSC 107 – Programming For Science. Today’s Goal  Discuss how to hand data to functions  Review loopholes in variables & scoping rules  Ways to get.
C++ for Engineers and Scientists Second Edition Chapter 8 I/O File Streams and Data Files.
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.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Spring 2013 Lecture 5: Continuing with C++ I/O Basics.
CSC 107 – Programming For Science. Today’s Goal  Discuss writing functions that return values  return statement’s meaning and how it works  When and.
CSC 107 – Programming For Science. Announcements.
PHY 107 – Programming For Science. The Week’s Goal.
Loops and Files. 5.1 The Increment and Decrement Operators.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Managers and “mentors” identified on projects page. All member accounts created and projects populated.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
Input/Output. Objectives In this chapter you will: Learn what a stream is and examine input and output streams Explore how to use the input stream functions.
Declaring fstream Objects An istream object named cin connects program and keyboard An ostream object named cout connects the program and the screen These.
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.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Lecture  I/O Streams  Console I/O  File I/O  Tools for File I/O  Sequential.
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.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students File Input and Output Checking input for errors.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
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.
CSC 107 – Programming For Science. Today’s Goal  Write functions that take & return values  How parameters declared and how we call functions  What.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Chapter Eight: Streams Slides by Evan Gallagher.
PHY 107 – Programming For Science. Today’s Goal  Get familiar with opening & closing files  Declaring variables for use with files  Using variables.
Chapter 14: Sequential Access Files
ifstreams and ofstreams
Auburn University COMP 3000 Object-Oriented Programming for Engineers and Scientists File I/O Dr. Xiao Qin Auburn University.
What is a File? A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused.
COMP 2710 Software Construction File I/O
Copyright © 2003 Pearson Education, Inc.
FILE INPUT OUTPUT Skill Area 315 Part B Materials Prepared by
File I/O.
Basic File I/O and Stream Objects
Today’s Lecture I/O Streams Tools for File I/O
when need to keep permanently
Chapter 3: Input/Output
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
File I/O in C++ I.
CPS120: Introduction to Computer Science
Reading from and Writing to Files
ifstreams and ofstreams
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Chapter 1 c++ structure C++ Input / Output
File I/O in C++ I.
Reading from and Writing to Files
Presentation transcript:

CSC 107 – Programming For Science

Today’s Goal  Get familiar with opening & closing files  Declaring variables for use with files  Using variables to open files for reading & writing  Closing files and understand why you should do so ALL  Understand what it means: ALL I/O is file I/O  Common bugs to avoid when coding with files in C++  Get a better understanding of what >> & << do  cin, cout are variables: know what their types are

Image To Sharpen  I have a (fuzzy) 1024 x 768 picture to sharpen 786,432  Only 786,432 numbers to type in to yesterday's lab  Will also need to click each pixel to update with result

More Data Entry Positions  Testing improved jet designs for oeingB-ay  Using program to simulate designs' lift & drag  5 possible designs (each 150MB) to test this iteration  Once results available, will tweak & retest designs  Need room of touch typists for all this data entry

This Is (Semi-Real) Problem  Large hadron collider eventually work as designed  No black hole when smashing particles at high speeds 28.5 GB/min  Creates 28.5 GB/min for nerds seeking truth & beauty

This Is (Semi-Real) Problem  Large hadron collider eventually work as designed  No black hole when smashing particles at high speeds 28.5 GB/min  Creates 28.5 GB/min for nerds seeking truth & beauty  Hired trained monkeys to type all 244,813,135,872 bits

This Is (Semi-Real) Problem  Large hadron collider eventually work as designed  No black hole when smashing particles at high speeds 28.5 GB/min  Creates 28.5 GB/min for nerds seeking truth & beauty  Hired trained monkeys to type all 244,813,135,872 bits college students

Yeah, Right  Real world demands we use files for most I/O  Data files used to start and/or end most projects  May contain: game levels, analysis results, CCD pics  Way to read & write files needed to be useful

Program Basics For Files  All built-in file I/O code means adding to header #include #include  Place with other #include s to use files in program  Even if no files are used, no cost to adding this line  Must specify namespace of file I/O code, also  If you really want, this can do this individually but… using namespace std; …much easier and probably habit by now anyway

Opening a File  To use file, we need variable to use in program  Numbers, cStrings, and booleans mixed in the file  Previous type (& arrays) do not make sense to use  C++ provides new types to refer to file itself

Types Used For Files  Within program, may use file in 2 possible ways  To read file, ifstream variables will be needed  Need variable of type ofstream to write to file

File Variable Declaration  Types are new, but still just declaring variables  Requires type & name of variable being declared  Names for human use; normal scoping rules apply  Cannot assign variables  Cannot assign variables but can use as parameters files are NOT numbers  Cannot use in equations: files are NOT numbers ofstream fout; ifstream fin; ofstream bob, bill, babs, barb; ifstream thisIsAFileVariable; ofstream monkey = "foo.txt"; ifstream fourFile = 4;

File Variable Declaration  Types are new, but still just declaring variables  Requires type & name of variable being declared  Names for human use; normal scoping rules apply  Cannot assign variables  Cannot assign variables but can use as parameters files are NOT numbers  Cannot use in equations: files are NOT numbers ofstream fout; ifstream fin; ofstream bob, bill, babs, barb; ifstream thisIsAFileVariable; ofstream monkey = "foo.txt"; ifstream fourFile = 4;

File Variable Declaration  Types are new, but still just declaring variables  Requires type & name of variable being declared  Names for human use; normal scoping rules apply  Cannot assign variables  Cannot assign variables but can use as parameters files are NOT numbers  Cannot use in equations: files are NOT numbers ofstream fout; ifstream fin; ofstream bob, bill, babs, barb; ifstream thisIsAFileVariable; ofstream monkey = "foo.txt"; ifstream fourFile = 4;

Name That File  Two ways to open a file once we have the name  No matter which used, must know name of file  Defaults to current directory, if only a name specified  By including in name, can use other directories  No standard way to do this – depends on the OS

Name That File  Two ways to open a file once we have the name  No matter which used, must know name of file  Defaults to current directory, if only a name specified  By including in name, can use other directories  No standard way to do this – depends on the OS

Opening the File  Can open file when variable declared char nameLoc[] = "bobbobbob"; char sndName[] = "csi.txt"; ifstream fin("image.dat"); ofstream fout(nameLoc); ifstream bobism(sndName); ofstream cookies(“nomnomnom.txt");  Even after declaration, files can be opened ifstream because; ofstream isaidso; because.open("mightMakes.right"); cin >> sndName; isaidso.open(sndName);

Did I Do Good?  May not always be successful opening a file  Cannot open and read file that does not exist  May not have permission to access a certain file  Cannot do impossible & write to nonexistent drive  Use built-in is_open function to check this  Called in manner similar to cout functions like setf  If variable attached to open file, function returns true  Returns false if variable not used to open file, yet  If attempt to open file fails, will also return false

Examples of is_open char sndName[]; ifstream because, foo("foo.txt"); ofstream isaidso, bar("snafu"); cout > sndName; isaidso.open(sndName); cout << because.is_open() << endl; cout << isaidso.is_open() << endl;

Upon Opening The Location Is…  Once open, read & write from start of file  As logical a choice as any other location to start at  If reading, can start getting all data from file  When writing to existing file what will happen?

Oops!

Opening a File  Within program, may use file in 2 possible ways  To read file, ifstream variables will be needed  Need variable of type ofstream to write to file

Opening a File  Within program, may use file in 2 possible ways  To read file, ifstream variables will be needed  Need variable of type ofstream to write to file  Open ofstream 2 different ways depending on use ofstream nukeIt("byebye.txt"); ofstream begone; begone.open("erasedOld.dat"); ofstream keepIt("saved", ios::app); ofstream faithAlone; faithAlone.open("preserve", ios::app); 3

Closing File  Important to close files once you are done  Program will delay saving data to make it faster  Crashes cause data loss if saves had been waiting  Until file is closed may be locked from other uses  Immediately saved on close, so insures data is safe  Can open more files if limit of open files reached ofstream giants("nlChamp"); ifstream yankees("evilEmpire"); phillies.close(); yankees.close();

Today's Key Point  Because of its history, all C++ I/O is file based  Obvious when file is source of data or target of write  But also true when reading from keyboard  Writing to screen also considered file I/O

Today's Key Point

What Are cin & cout ?  Statement needed for most file I/O #include  To use cin & cout we must have statement: #include

What Are cin & cout ?  Statement needed for most file I/O #include  To use cin & cout we must have statement: #include  There is a method: similarity not an accident  cin & cout are file variables defined by system

What Are cin & cout ?  Statement needed for most file I/O stream #include  To use cin & cout we must have statement: stream #include  There is a method: similarity not an accident  cin & cout are file variables defined by system

Deep in Bowels of iostream  In iostream find 2 lines to be included in code: ifstream cin( ); ofstream cout( );  Already written code reading from a file  Use ifstream like cin to read ASCII text in a file  Also know how to write ASCII text to a file  As with cout, ofstream s writes text to a file

Read User's Typing With cin  Used to read one or more values at once: cin >> variable ; cin >> variable1 >> variable2 ;  Starts where last read stopped reading input  Automatically skips past whitespace  Data type of variable determines what is read  Stops at first non-usable value found in the input  If input is not usable, will set variable equal to 0

Read File W/ ifstream Variable  Used to read one or more values at once: ifstream myFile; myFile >> variable ; myFile >> variable1 >> variable2 ;  Starts where last read stopped reading input  Automatically skips past whitespace  Data type of variable determines what is read  Stops at first non-usable value found in the input  If input is not usable, will set variable equal to 0

Print to Screen Using cout  Easy to output: print text using cout cout << “Hello World” << endl;  Prints out whatever is placed between quotes  Value of variable printed if variable not in quotes  Use escape sequences for fancier text output \n  newline (move to start of next line) \t  tab (go to next column that is multiple of 8)  Output using #include fancier

Print to File With ostream  Easy to output: output via ostream variable ofstream outFile; outFile << “Hello World” << endl;  Prints out whatever is placed between quotes  Value of variable printed if variable not in quotes  Use escape sequences for fancier text output \n  newline (move to start of next line) \t  tab (go to next column that is multiple of 8)  Output using #include fancier

See How Easy It Is? #include #include using namespace std; int main(void) { int sum = 0; int val; cout > val; while (val != -1) { sum += val; cout > val; } return 0; }

See How Easy It Is? #include #include using namespace std; int main(void) { ifstream fin; ofstream fout; int sum = 0; int val; fout > val; while (val != -1) { sum += val; fout > val; } return 0; }

And When We Run It? #include #include using namespace std; int main(void) { ifstream fin; ofstream fout; int sum = 0; int val; fout > val; while (val != -1) { sum += val; fout > val; } return 0; }

And When We Run It?

Must Open File Before Using  How file opened unimportant, just that is open  Open when declared, by giving file name as cString ifstream bobIn("file.txt"); ofstream whyNot(stringFromUser);  Open open later in program using open() routine bobIn.open(nameOfDataFile); whyNot.open("averagesWeCompute");  Variable must refer to open file or else it crashes  Often add check with is_open() to protect from crashs

See How Easy It Is? #include #include using namespace std; int main(void) { int sum = 0; int val; cout > val; while (val != -1) { sum += val; cout > val; } return 0; }

See How Easy It Is? #include #include using namespace std; int main() { int sum = 0; int val; cout > val; while (val != -1) { sum += val; cout > val; } return 0; }

See How Easy It Is? #include #include using namespace std; int main() { ifstream myFile("numbers.txt"); ofstream yNot("sums.out"); if (myFile.is_open() && yNot.is_open()) { int sum = 0; int val; yNot > val; while (val != -1) { sum += val; yNot > val; } } return 0; }

See How Easy It Is? #include #include using namespace std; int main() { ifstream myFile("numbers.txt"); ofstream yNot("sums.out"); if (myFile.is_open() && yNot.is_open()) { int sum = 0; int val; cout > val; while (val != -1) { sum += val; yNot > val; } } return 0; }

Variables are Variables  Like all variables, can use files as parameters  Argument must also be file variable for it to compile  Reading & writing continues through the function  Can only go forward in file no matter what  Within the function, "file position marker" continues  Cannot unring bell, does not overwrite file on return  As with cin to read, will not reread after function

But…  Like all variables, can use files as parameters  Argument must also be file variable for it to compile  Reading & writing continues through the function  Can only go forward in file no matter what  Within the function, "file position marker" continues  Cannot unring bell, does not overwrite file on return  As with cin to read, will not reread after function

But…  Like all variables, can use files as parameters  Argument must also be file variable for it to compile  Reading & writing continues through the function  Can only go forward in file no matter what  Within the function, "file position marker" continues  Cannot unring bell, does not overwrite file on return  As with cin to read, will not reread after function

Butt…  Like all variables, can use files as parameters  Argument must also be file variable for it to compile  Reading & writing continues through the function  Can only go forward in file no matter what  Within the function, "file position marker" continues  Cannot unring bell, does not overwrite file on return  As with cin to read, will not reread after function

Variables are Variables  Like all variables, can use files as parameters  Argument must also be file variable for it to compile  Reading & writing continues through the function  Can only go forward in file no matter what  Within the function, "file position marker" continues  Cannot unring bell, does not overwrite file on return  As with cin to read, will not reread after function PARAMETER MUST BE PASS-BY-REFERENCE

Your Turn  Get into your groups and try this assignment

For Next Lecture  Another use of data files in Section  Must we use text or are there faster approaches?  What was the point of learning binary numbers?  Could we predict size of file we read/write in program?  Weekly Assignment uses Xcode this week  Submit via ; CloudCoder cannot use files  Programming Assignment #3 available Friday