Title: COMP102 Session 3A
1COMP102 Session 3A
- Lab07 Score Management Gadget
2File I/O
- File
- External collection of data
- Provided input to a program
- Stored output from a program
- Stored on secondary storage permanently
- Must be
- Opened before used
- Closed after used
- File I/O
- Operation related to file
3Stream
- Sequence of characters
- ltiostreamgt user interactive
- cin
- Input stream associated with keyboard
- cout
- Output stream associated with display
- ltfstreamgt file operation
- ifstream
- Defined input stream associated with file
- ofstream
- Defined output stream associated with file
4File Stream
- Before
- Getting data from a file
- Output data to a file
- Declare a stream object
- Creating a channel
- Associate this stream object to the file
- Connecting the stream component to the file with
program
5File Stream
include ltfstreamgt ifstream fin fin.open("fil
ename.txt") // connects stream fsIn to the
external // file "filename.txt" fin.close() //
disconnects the stream and associated file
6Input File
- Include the ltfstreamgt
- include ltfstreamgt
- Declare an input stream object
- ifstream fin
- Open an dedicated file
- fin.open(filename.txt)
- Get character from file
- fin.get(character)
- Close the file
- fin.close()
7Output File
- Include the ltfstreamgt
- include ltfstreamgt
- Declare an output stream object
- ofstream fout
- Open an dedicated file
- fout.open(filename.txt)
- Put character from file
- fout.put(character)
- Close the file
- fout.close()
8File I/O Function
- Input file
- fin.eof()
- Test for end-of-file condition
- fin.get(char character)
- Obtains the next character from the file stream
- Put into the variable character
- Output file
- fout.put(char character)
- Inserts character to the output file stream
9File I/O More Function
ifstream fin char character
fin.open(data.txt) // open the file
fin.get(character) // get the first char
while(!fin.eof()) // loop to read each
character fin.get(character)
fin.close()
10Stream Manipulators
- Used to manage the input and output format of a
stream - With the directive ltiomanipgt
- E.g.
- cout ltlt endl
- cout ltlt hex
- cout ltlt setw(5)
11Stream Manipulators
- include ltiomanipgt
- setprecision(d)
- Set number of significant digits to d
- setw(w)
- Set field width to w
- setfill(c)
- Set fill character to c
- setiosflags(f)
- Set flag f to 1
- resetiosflags(f)
- Set flag f to 0
12Stream Manipulators
int a 1234567 int b 10 cout ltlt hex
ltlt a ltlt endl cout ltlt setiosflags(iosshowpos)
ltlt b ltlt endl cout ltlt resetiosflags(iosshowpos
) cout ltlt setiosflags(iosscientific) ltlt b
ltlt endl
13SUMMARY
- By the end of this lab, you should be able to
- Read/Write/Manipulate file with directive
- ltfstreamgt
- Formatting input and output stream with directive
- ltiomanipgt