Text Files and Streams - PowerPoint PPT Presentation

1 / 25
About This Presentation
Title:

Text Files and Streams

Description:

Sequence of data (bytes) coming from a source & waiting to be moved to ... When function returned, copy would vanish, and so. would any changes. 23. Example. 24 ... – PowerPoint PPT presentation

Number of Views:84
Avg rating:3.0/5.0
Slides: 26
Provided by: jian9
Category:
Tags: files | streams | text | vanish

less

Transcript and Presenter's Notes

Title: Text Files and Streams


1
Chapter 11
Text Files and Streams
2
Outline
  • Streams and Stream Variables (Objects)
  • Input (read) from a File
  • Header Technique
  • End-of-File (EOF) Technique
  • How a Text File is Stored
  • Output (write) to a File
  • Streams as Function Parameters
  • Inheritance and Stream Parameters
  • More Member Functions for Streams

3
Streams
  • What Is a Stream?
  • Sequence of data (bytes) coming from a source
    waiting to be moved to a destination
  • Predefined Streams
  • Predefined by the stream libraries for everyones
    use
  • cin
  • Stream of bytes coming from keyboard to your
    program
  • cout
  • Stream of bytes going from your program to
    monitor

4
Stream Variables Are Objects
  • Instances of a Class
  • Lots of different I/O classes defined in C
  • istream ostream general input output
    streams
  • cin is an istream, and cout is an ostream
  • ifstream ofstream input output file
    streams
  • Objects More Complex than Variables
  • Contain 2 kinds of things
  • Attributes member variables (data describing
    the stream)
  • Methods member functions (actions on that
    data)
  • Each object contains different data in its
    member variables than all the other objects
    usually

5
Stream Variables (Objects)
  • Stream objects are declared just like variables
  • Example ifstream In_File
  • Using an objects Member Functions
  • Syntax object_name.member_function(arguments)
  • Have to specify
  • Which object youre talking about
  • Which of that objects functions youre using
  • What information that function needs to do its
    job
  • example
  • In_File.open("Data_File.txt")
  • Talking about ifstream object In_File
  • Using that objects open function
  • Passing it the disk pathname of the file to be
    opened

6
We Want To
  • be able to read from, write to, control disk
    files as streams
  • Open any disk file so it works like a stream
    for reading or writing
  • Provide the names of our disk files when we write
    the program or ask for a files name at run time
  • Be able to detect problems (file not found, tried
    to read past end-of-file, etc.)
  • Create new files, read files, overwrite existing
    files, append new data onto the end of existing
    files
  • Pass a file to a function for it to process
  • Have more than one file open at the same time

7
Input from a File Stream
8
Input from a File - Basic Steps
  • // 1. Include the library fstream
  • include ltfstreamgt
  • int main()
  • // 2. Open a file for input
  • ifstream exams_in // declares the file stream
    object
  • exams_in.open(exam.dat) // attaches stream
    object to an file
  • // 3. Read from the file stream
  • exams_in gtgt num_exams
  • ... ...
  • // 4. Close the file stream
  • exams_in.close() // detaches the stream from
    the file exam.dat

9
Example
Header of exam.dat tells how many
scores follow
Specify the path (directory)
exams_in.open ("C\\csci1010\\exam.dat")
10
Protecting against a nonexistent file
  • Using cerr and abort

fail() returns 1 if the open() function failed
cerr is predefined in iostream
terminates the program we need include ltcstdlibgt
  • Using the assert function
  • Primarily designed for use in debugging
  • Causes immediate program termination
  • Issues general error message
  • we need include ltcassertgt

Things are okay if the open operation did NOT fail
11
Input from a File End-of-File (EOF)
  • Not convenient to provide a header at the
    beginning of a file
  • Might miscount when the file contains a large
    number of data groups (records)
  • Addition / deletion requires the header to be
    changed
  • The program detects when an attempt to read past
    the end of the file has occurred

12
Example
eof() returns 1 only when an input operation has
already attempted to read past the end of the file
ws is whitespace manipulator that skip over
whitespace characters ( , \t, \n)
13
Structure of a Text File
(\n characters)
(EOF)
(current position pointer)
  • Text lines separated by newline (\n) characters
  • Can be read written just like any other
    character
  • File ended by EOF condition (not a character)
  • wage_in gtgt name gtgt hours gtgt rate
  • wage_in gtgt ws

14
Example Other ways to do this
At EOF, the gtgt operator returns 0 (false) So
well just read the next datum we want
while (wage_in gtgt name gtgt hours gtgt rate) pay
hours rate cout ltlt name ltlt ltlt pay ltlt
endl
skips any whitespace, then checks for EOF
15
More about Function eof ()
  • It only works if program has bumped its nose -
    trying to read past end of the file
  • If you read the last character of a file, but
    dont try to read past that, eof () returns
    false (meaning not yet)
  • This is also true of the gtgt operator
  • Most useful with fstream classs member functions
  • They dont automatically return a detectable
    value,so you dont know whether they hit EOF
    without testing

16
Entering File Names Interactively
  • What if we dont know the file name when we write
    the program?
  • We get the file name from somewhere (like the
    user), and put it into a string object

But the open() function does NOT know from C
strings because it uses (old) C-language string
have to use .c_str() to extract the (old)
C-language string from a C string
17
Output to a File Stream
18
Output (Write) to Files
  • Writing to a New File (or Replacing an Existing
    Files Contents)
  • ofstream fout // declares a output stream
  • fut.open ("Output.txt", iostrunc) // attaches
    the file
  • if (!fout.fail())
  • fout ltlt "This replaces contents of Output.txt
    ltlt endl
  • fout.close () // detaches and save the file
  • Appending to an Existing File
  • ofstream fout
  • fout.open ("Output.txt", iosapp)
  • if (!fout.fail())
  • fout ltlt "This goes onto the end of Output.txt"

default
appendonto the end
19
Updating Files
20
More about Opening Closing Files
  • string Word
  • ifstream fin ("In1.txt") // open In1.txt when
    declaring fin
  • ofstream fout ("Out1.txt")
  • while (fin gtgt Word)
  • fout ltlt Word ltlt endl
  • fin.close () // Finished with
    In1.txt
  • fout.close () // Finished with
    Out1.txt
  • fin.open("In2.txt") // Now open In2.txt
    for reading
  • fout.open ("Out2.txt, // And append to
    Out2.txt
  • iosapp)
  • while (fin gtgt Word)
  • fout ltlt Word ltlt endl

change file settings (e.g., whether to start
writing to an output file at the beginning or
append onto the end) by using specially-defined
const values as the 2nd parameter to the open
call.
21
Passing a File to Functions (1)
  • What to Pass?
  • file name
  • file stream object
  • If we use file name, function has to open
    and close file in addition to doing its real job
  • Using file stream object usually makes more sense
  • Caller takes care of opening file, verifying that
    its there, etc.
  • Function just does its thing on the file
    whichever file it is

22
Passing Files to Functions (2)
  • RULE file stream objects MUST be passed
    by reference, not by value
  • Even if contents of disk file itself may not
    change, files member functions must be able to
    change current position pointer
  • Member functions called from your function
    must have direct access to the file/stream
    object which is only possible when passed by
    reference
  • If we passed it by value
  • Function would get a copy of file/stream object
  • Any changes would get made to the copy, not the
    original
  • When function returned, copy would vanish, and
    so would any changes

23
Example
24
Inheritance and Stream Parameters
ios
istream
ostream
iostream
ifstream
ofstream
25
More fstream Member Functions
  • For use when gtgt ltlt wont do
  • Single-character I/O
  • char Ch
  • ifstream File_In
  • ofstream File_Out
  • File_In.get(Ch) // Even gets whitespace chars.
  • File_Out.putback(Ch) // at the front
  • Text-line input
  • string Buffer
  • ifstream File_In
  • getline (File_In, Buffer)
  • Gets characters from In_File into Buffer,
    stopping at next '\n'
  • Does not copy the '\n' into the buffer
  • Leaves current position pointer pointing after
    the '\n'
Write a Comment
User Comments (0)
About PowerShow.com