File Input and Output in C - PowerPoint PPT Presentation

1 / 26
About This Presentation
Title:

File Input and Output in C

Description:

Much like the string type, streams are OBJECTS ... Convert string fileName to a C string type. inFile.open(fileName.c_str()); 22 ... – PowerPoint PPT presentation

Number of Views:44
Avg rating:3.0/5.0
Slides: 27
Provided by: ryanmck
Category:
Tags: file | input | output | string

less

Transcript and Presenter's Notes

Title: File Input and Output in C


1
  • File Input and Output in C

2
How much Data?
  • For very small amounts of data, just code it into
    the program x 5
  • For small amounts of data, ask the user to type
    it in cin gtgt x gtgt y gtgt z
  • For medium and large amounts of data, what do you
    do? An EXTERNAL FILE
  • They are stored on secondary storage, like a hard
    drive or memory stick or floppy
  • They can have more data than RAM can hold!

3
Why external files?
  • Handles large amounts of data
  • Storage of data independent of the program, so
    program doesnt have to be changed if data
    changes
  • Easier to edit the data
  • Can use the same data as input for different
    programs
  • Can save output data for use later
  • Can use output of one program as input of another

4
Keyboard and Screen I/O
0
  • include ltiostreamgt

4
5
File I/O
0
  • include ltfstreamgt

output data
input data
executing program
Report.txt
Input.txt
stream variable (of type ofstream)
stream variable (of type ifstream)
5
6
Using File I/O
  • Include Library include ltfstreamgt
  • Declare your file streams - choose valid,
    meaningful identifiers for them and the types
    ifstream and ofstream
  • Open the files (associate disk files with file
    streams)
  • Use your file stream identifiers in your I/O
    statements (using gtgt and ltlt , manipulators, get,
    ignore, etc)
  • Close the files when done with them

6
7
File I/O Statements
  • include ltfstreamgt
  • // Declare File Streams
  • ifstream myInfile // for input
  • ofstream myOutfile // for output
  • myInfile.open(myIn.dat) // Open input file
  • myOutfile.open(myOut.dat) // Open output file
  • // Use file streams for input and output
  • // Close files
  • myInfile.close()
  • myOutfile.close()

7
8
File Stream Variables
  • File Streams are Variables
  • cin and cout are automatically created
  • You must declare your own stream variables to use
    file I/O
  • For Input
  • Variable type is ifstream (input file stream)
  • For Output
  • Variable type is ofstream (output file stream)

9
ifstream and ofstream objects
  • Much like the string type, streams are OBJECTS
  • Recall that C objects combine data and
    functionality (built-in member functions)
  • When you declare an ifstream or ofstream
    variable, that variable has built-in
    functionality
  • open, close, etc

10
Opening a File
  • Opening a file
  • Associates your file stream variable with the
    external (disk) name for the file
  • If the input file does not exist on disk, open is
    not successful (fail state!)
  • If the output file does not exist on disk, a new
    file with that name is created
  • If the output file already exists, it is erased!
  • stream_name.open( file_name )

10
11
REMEMBER!
  • File input and output streams work exactly the
    same as cin and cout
  • You can use the same input commands
  • gtgt, get, getline, etc
  • You can use the same output commands and
    modifiers
  • ltlt, endl, fixed, showpoint, setprecision, setw,
    etc
  • Simply replace cin or cout with your custom
    declared stream variable

12
Whats a Buffer?
  • Hard drives are slow, CPU and RAM are fast
    bottleneck
  • If you're getting some data from HD, why not get
    a good-sized amount of it?
  • The OS sets aside some RAM (buffer) and stores
    the file data in it until your program asks for
    it, then provides it as requested
  • If the buffer empties then OS gets some more from
    the hard drive

12
13
Buffer?
  • The OS maintains a "buffer pointer" which keeps
    track of what characters have been given to the
    program and which haven't
  • The pointer tells the OS when the buffer is empty
  • All input and output functions affect (move) the
    buffer pointer

13
14
File Input
  • When a file is opened using an ifstream object, a
    buffer-full of data is pulled in from the
    secondary storage device
  • A buffer pointer is placed in the stream at the
    beginning of the file contents
  • Input commands issued on the stream affect the
    buffer pointer position in the buffer
  • Sequential access, starts at front of buffer,
    moves pointer forward through data

15
Input Statements
0
  • SYNTAX
  • These examples yield the same result.
  • fileIn gtgt length
  • fileIn gtgt width
  • fileIn gtgt length gtgt width

ifstream fileIn fileIn.open(myFile.txt) fileIn
gtgt Variable gtgt Variable . . .
15
16
In the file you have AspaceBspaceCEnter
0
char first char middle char last
fileIngtgtfirst fileIngtgtmiddle
fileIngtgtlast NOTE The buffer pointer is
still pointing to the trailing newline
character in the input stream
first
middle
last
A
B
C
first
middle
last
16
17
Another example using gtgt
0
STATEMENTS CONTENTS POINTER
POSITION int i 25 A\n char
ch 16.9\n float x fileIn gtgt i
25 A\n 16.9\n fileIn gtgt
ch 25 A\n 16.9\n fileIn gtgt
x 25 A\n 16.9\n
25
16.9
17
18
Common Input mistake
  • You open the file stream infile for input
  • But then your input statements are for CIN
  • You didn't print a prompt since you shouldn't
    need one - you're reading from a FILE
  • The program appears to "hang" because it is
    waiting for KEYBOARD input! there's no prompt so
    you don't know it's waiting

19
File Output
  • When a file is opened using an ofstream object,
    any output inserted into that stream is placed
    into the file buffer rather than on the screen
  • HINT the contents of the output file will appear
    exactly as it would have appeared if it were
    placed on the monitor
  • first try the output using cout to verify it
  • once it is to your liking, change the stream name
    to your output file

20
File Output
  • Your output file buffer is filled by program
    commands like ltlt or manipulators (endl)
  • Output data is placed into a disk file from your
    output file buffer when the buffer is full or
    when the program ends

20
21
Output Statements
  • SYNTAX
  • These examples yield the same output
  • fileOut ltlt The answer is
  • fileOut ltlt 3 4
  • fileOut ltlt The answer is ltlt 3 4

ofstream fileOut fileOut.open(outfile.txt) fil
eOut ltlt Expression ltlt Expression . . .
22
Run Time File Name Entry
If you do not know up front what the name of the
file to open will be, you can have the user enter
the file name at the keyboard into a string.
  • include ltstringgt
  • // Contains conversion function c_str
  • ifstream inFile
  • string fileName
  • cout ltlt Enter input file name ltlt endl //
    Prompt
  • cin gtgt fileName
  • // Convert string fileName to a C string type
  • inFile.open(fileName.c_str())

22
23
Stream Fail State
  • When a stream enters the fail state,
  • Further I/O operations using that stream have no
    effect at all
  • The computer does not automatically halt the
    program or give any error message!!
  • Possible reasons for entering fail state include
  • Invalid input data (often the wrong type)
  • Opening an input file that doesnt exist
  • Opening an output file on a disk that is already
    full or is write-protected

23
24
Checking for a stream in fail state
  • There are two ways that are equivalent to each
    other, both use bool functions
  • These checks can be done at any point in the
    program.
  • To abort the program you would use
  • return 1
  • this only works from inside the main function.
  • DO NOT OVERUSE this ability!! It violates
    structured programming!

25
Checking for a stream in fail state
  • First way
  • Assuming myfile is declared as a filestream,
    either input or output,
  • myfile.fail() returns true if the stream has
    failed, false otherwise
  • if (myfile.fail())
  • cout ltlt filestream failed ltlt endl
  • return 1 // 1 to indicate something went wrong

26
Checking for a stream in fail state
  • Second way
  • Assuming myfile is declared as a filestream,
    either input or output,
  • myfile (the name of the stream) is also
    considered a bool variable. It has the value
    true if the stream is good, false if failed
  • if (!myfile)
  • cout ltlt filestream failed ltlt endl
  • return 1 // 1 to indicate something went wrong
Write a Comment
User Comments (0)
About PowerShow.com