Title: COMP102 Lab 7
1COMP102 Lab 7
2File I/O
- The file operations always follow the following
sequences - Open the file
- Read/write the file contents
- Close the file
- REMEMBER to close the file. Otherwise, the
contents may be lost!
3eof()
- A function which return 1/true if the ifstream
HAS reached the end of the file - ifstream will NOT know it has reached the end
untill it has tried to read something from the
file
4Example
- Suppose there are 2 characters in the file a.txt
- What will bethe output of the following code
segment?
ifstream fin char c fin.open("a.txt") while
(!fin.eof()) fin.get(c) cout ltlt
c cout ltlt "end" ltlt endl fin.close()
ab
a.txt
5Example
- The output will be something like this
- There is an extra space between ab and end
- The extra space is actually the EOF character
- Why??
ab end
6Example
- Lets add some code to display the value of eof()
ifstream fin char c fin.open("a.txt") while
(!fin.eof()) cout ltlt "BEFORE get() eof()"
ltlt fin.eof() ltlt endl fin.get(c) cout ltlt
"c" ltlt c ltlt endl cout ltlt " AFTER get()
eof()" ltlt fin.eof() ltlt endl cout ltlt "end" ltlt
endl fin.close()
7Example
BEFORE get() eof()0 ca AFTER get()
eof()0 BEFORE get() eof()0 cb AFTER get()
eof()0 BEFORE get() eof()0 c AFTER get()
eof()1 end
8Explanation
- Before each iteration, the condition in while
loop will be evaluated - The loop body will be executed only when the
condition is true, i.e. eof() 0 or false - While a character is successfully read from the
file stream, the value of eof() will not change,
even it is the last character of the file - ifstream will change the return value of eof()
only when no more character can be read. In other
words, an attempt to get a character is required
9Explanation
- Therefore, the character collected from get() in
the loop body may NOT be valid - get() will return -1 if no more character can be
read from the file stream - There are a number of ways to verify if the
character collected from get() is valid or not - Add an extra eof() check after get()
- Use the return value of get()
10Solution 1 Extra eof() Check
ifstream fin char c fin.open("a.txt") while
(!fin.eof()) fin.get(c) if
(!fin.eof()) cout ltlt c cout ltlt "end" ltlt
endl fin.close()
11Solution 2 Return Value of get()
ifstream fin char c fin.open("a.txt") while
(!fin.eof()) if (fin.get(c)) cout ltlt
c cout ltlt "end" ltlt endl fin.close()