C++-Course(7).ppt

上传人:本田雅阁 文档编号:2697961 上传时间:2019-05-05 格式:PPT 页数:59 大小:1.98MB
返回 下载 相关 举报
C++-Course(7).ppt_第1页
第1页 / 共59页
C++-Course(7).ppt_第2页
第2页 / 共59页
C++-Course(7).ppt_第3页
第3页 / 共59页
C++-Course(7).ppt_第4页
第4页 / 共59页
C++-Course(7).ppt_第5页
第5页 / 共59页
点击查看更多>>
资源描述

《C++-Course(7).ppt》由会员分享,可在线阅读,更多相关《C++-Course(7).ppt(59页珍藏版)》请在三一文库上搜索。

1、,Chapter 14: Streams and File I/O,Outline,I/O Streams Tools for Stream I/O Stream Hierarchies Random Access to Files Summary,I/O Streams,Introduction Streams Special objects Deliver program input and output File I/O Use inheritance File I/O very useful, so covered here Streams A flow of characters I

2、nput stream,I/O Streams,Flow into program Can come from keyboard Can come from file Output stream Flow out of program Can go to screen Can go to file Streams usage Weve used streams already cin,I/O Streams,Input stream object connected to keyboard cout Output stream object connected to screen Can de

3、fine other streams To or from files Used similarly as cin, cout Streams usage like cin, cout Consider: Given program defines stream inStream that comes from some file:,I/O Streams,int theNumber; inStream theNumber; Read value from stream, assigned to theNumber Program defines stream outStream that g

4、oes to some file outStream “theNumber is “ theNumber; Write value to stream, which goes to file Files Well use text files Reading from file,I/O Streams,When program takes input Writing to file When program sends output Start at beginning of file to end Other methods available Well discuss this simpl

5、e text file access here File connection Must first connect file to stream object For input: File ifstream object,I/O Streams,For output: File ofstream object Classes ifstream and ofstream Defined in library Named in std namespace File I/O libraries To allow both file input and output in your program

6、: #include using namespace std; or,I/O Streams,#include using std:ifstream; using std:ofstream; Declaring streams Stream must be declared like any other class variable: ifstream inStream; ofstream outStream; Must then “connect“ to file: inStream.open(“infile.txt“); Called “opening the file“,I/O Stre

7、ams,Use member function open Can specify complete pathname Streams usage Once declared use normally! int oneNumber, anotherNumber; inStream oneNumber anotherNumber; Output stream similar: ofstream outStream; outStream.open(“outfile.txt“); outStream “oneNumber = “ oneNumber,I/O Streams, “ anotherNumb

8、er = “ anotherNumber; Send items to output file File names Programs and files Files have two names to our programs External file name Also called “physical file name“ Like “infile.txt“ Sometimes considered “real file name“ Used only once in program (to open),I/O Streams,Stream name Also called “logi

9、cal file name“ Program uses this name for all file activity Closing files Files should be closed When program completed getting input or sending output Disconnect stream from file In action: inStream.close();,I/O Streams,outStream.close(); Note no arguments Files automatically close when program end

10、s File flush Output often “buffered“ Temporarily stored before written to file Written in “groups“ Occasionally might need to force writing: outStream.flush(); Member function flush, for all output streams,I/O Streams,All buffered output is physically written Closing file automatically calls flush()

11、 File example See the next slide.,I/O Streams,I/O Streams,I/O Streams,Appending to a file Standard open operation begins with empty file Even if file exists contents lost Open for append: ofstream outStream; outStream.open(“important.txt“, ios:app); If file doesnt exist create it If file exists appe

12、nd to end 2nd argument is class ios defined constant In library, std namespace,I/O Streams,Example of appending to a file See the next slide.,I/O Streams,I/O Streams,I/O Streams,Alternative syntax for file opens Can specify filename at declaration Passed as argument to constructor ifstream inStream;

13、 inStream.open(“infile.txt“); equivalent to: ifstream inStream(“infile.txt“); Checking file open success File opens could fail If input file doesnt exist,I/O Streams,No write permissions to output file Unexpected results Member function fail() Place call to fail() to check stream operation success i

14、nStream.open(“stuff.txt“); if (inStream.fail() cout “File open failed.n“; exit(1); ,I/O Streams,Example of checking file open See the next slide.,I/O Streams,I/O Streams,I/O Streams,Character I/O with files All cin and cout character I/O same for files! Member functions work same: get, getline put,

15、putback, peek, ignore Checking end of file Use loop to process file until end Typical approach Two ways to test for end of file,I/O Streams,First method Member function eof() inStream.get(next); while (!inStream.eof() cout next; inStream.get(next); Reads each character until file ends eof() member f

16、unction returns bool,I/O Streams,End of file check with read Second method read operation returns bool value! (inStream next) Expression returns true if read successful Returns false if attempt to read beyond end of file In action: double next, sum = 0; while (inStream next) sum = sum + next; cout “

17、the sum is “ sum endl;,I/O Streams,Example of checking end of file See the next slide.,I/O Streams,I/O Streams,I/O Streams,Tools for Stream I/O,Tools: file names as input Stream open operation Argument to open() is string type Can be literal (used so far) or variable char fileName16; ifstream inStre

18、am; cout fileName; inStream.open(fileName); Provide more flexibility,Tools for Stream I/O,Formatting output with stream functions Recall previous “magic formula“: cout.setf(ios:fixed); cout.setf(ios:showpoint); cout.precision(2); Output numbers in “money“ form (12.52) Can use on any output stream Fi

19、le streams have same member functions as cout object,Tools for Stream I/O,Output member functions Consider: outStream.setf(ios:fixed); outStream.setf(ios:showpoint); outStream.precision(2); Member function precision(x) Decimals written with “x“ digits after decimal Member function setf() Allow multi

20、tude of output flags to be set,Tools for Stream I/O,More output member functions Consider: outStream.width(5); Member function width(x) Sets width to “x“ for outputted value Only affects “next“ value outputted Must set width before each value in order to affect all Typical to have “varying“ widths T

21、o form “columns“,Tools for Stream I/O,Flags Recall: member function setf() Set condition of output flags All output streams have setf() member Flags are constants in class ios In library , std namespace setf() examples Common flag constants: outStream.setf(ios:fixed); Set fixed-point notation (decim

22、al),Tools for Stream I/O,outStream.setf(ios:showPoint) Always include decimal point outStream.setf(ios:right); Set right-justification Set multiple flags with one call: outStream.setf(ios:fixed | ios:showpoint | ios:right); Manipulators Manipulator defined: “A function called in nontraditional way“

23、Can have arguments,Tools for Stream I/O,Placed after insertion operator Do same things as member functions! In different way Common to use both “together“ setw() and setprecision() are in library , std namespace Manipulator example: setw() setw() manipulator: cout “Start“ setw(4) 10 setw(4) 20 setw(

24、6) 30;,Tools for Stream I/O,Results in: Start 10 20 30 Note: setw() affects only next outputted value Must include setw() manipulator before each outputted item to affect all Manipulator setprecision() setprecision() manipulator: cout.setf(ios:fixed | ios:showpoint); cout “$“ setprecision(2) 10.3 “

25、“ “$“ 20.5 endl;,Tools for Stream I/O,Results in: $10.30 $20.50 Saving flag settings Flag settings “stay“ until changed Precision and setf flags can be saved and restored Function precision() returns current setting if called with no arguments Member function flags() provides similar capability Savi

26、ng flag settings example,Tools for Stream I/O,void outputStuff(ofstream Function to save & restore “typical“ settings,Tools for Stream I/O,Call: outputStuff(myStream); Restoring default setf settings Can also restore default settings: cout.setf(0, ios:floatfield); Not necessarily the “last“ setting!

27、 Default values are implementation - dependent Does not reset precision settings Only setf settings Example of formatting output See the next slide.,Tools for Stream I/O,Tools for Stream I/O,Tools for Stream I/O,Tools for Stream I/O,Stream Hierarchies,Basic concepts Class Relationships “Derived from

28、“ One class obtained from another class Then features are “added“ Example: Input file streams class is derived from class of all input streams It then adds open and close member functions i.e.: ifstream is derived from istream,Stream Hierarchies,Class inheritance “real“ example Class of all converti

29、bles (活动顶蓬式汽车) is derived from class of all automobiles Every convertible is an automobile Convertible “adds features“ to automobile Stream class inheritance Consider: If D is derived class of class B All objects of type D are also of type B e.g., A convertible is also an automobile,Stream Hierarchi

30、es,Regarding streams: An ifstream object is also an istream object Should use istream objects for parameters More objects can be plugged in! Stream class inheritance example See the next slide.,Stream Hierarchies,Stream Hierarchies,Stream class inheritance example calls Considering previous function

31、s: twoSumVersion1(fileIn); / Legal! twoSumVersion1(cin); / Illegal! Because cin is not of type ifstream! twoSumVersion2(fileIn); / Legal! twoSumVersion2(cin); / Legal! More versatile istream parameter accepts both objects,Random Access to Files,Basic concepts Sequential Access Most commonly used Ran

32、dom Access Rapid access to records Perhaps very large database Access “randomly“ to any part of file Use fstream objects input and output,Random Access to Files,Random access tools Open same as istream or ostream Add second argument fstream rwStream; rwStream.open(“stuff“, ios:in | ios: out); Open w

33、ith read and write capability Move about in file rwStream.seekp(1000); Position put-pointer at 1000th byte rwStream.seekg(1000);,Random Access to Files,Position get-pointer at 1000th byte Random access sizes To move about must know sizes sizeof() operator determines number of bytes required for an o

34、bject: sizeof(s) / Where s is string s = “Hello“ sizeof(10) sizeof(double) sizeof(myObject) Position put-pointer at 100th record of objects:,Random Access to Files,rwStream.seekp(100 * sizeof(myObject) 1);,Summary,Streams connect to files with open operation Member function fail() checks successes S

35、tream member functions format output e.g., width, setf, precision Same usage for cout (screen) or files Stream types can be formal parameters But must be call-by-reference istream (no “f“) parameters accept cin or ifstream objects as arguments ostream (no “f“) parameters accept cout or ofstream,Summ

36、ary,objects as arguments Member function eof Used to test for end of input file,Assignment,Self-Test Exercises 2, 4, 6, 8, 10, 12, 14 Programming Project Read and merge numbers from two files into a third file. The two files are to be sorted, and the merge is to leave the third file sorted. Note: The deadline of the submission is due on June, 16, 2013.,

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 其他


经营许可证编号:宁ICP备18001539号-1