Professional Documents
Culture Documents
Week 13
File stream
Note
• Stream: 串流
• Permissions: 權限
• Handle: 處理
Outline
• File stream
• Open and close file
• Read file
• Write file
• Practice
Open and close file
• From the form of file storage, we can divide the data that
exists on the hard disk into two categories, binary files and
string files:
• binary file: Any executable application is a binary file.
• string file: A file stored in a string format that can be read
or written again by an application.
fstream
• This data type represents the file stream generally, and has
the capabilities of both ofstream and ifstream which means it
can create files, write information to files, and read
information from files.
Open file
• A file must be opened before you can read from it or write to it.
• the first argument specifies the name and location of the file to be
opened and the second argument of the open() member function defines
the mode in which the file should be opened.
• file.open(file_name, mode);
• Permissions are divided into fstream::in (read file mode), fstream::out
(overwrite old file mode), If both are enabled it can be written as
fstream::in | fstream::out.
• If the mode of writing is not to overwrite the old content, but to write
the new content after the old content, you need to replace fstream::out
with fstream::app.
• If the write mode is set, and the original file with the file name does not
exist, the system will automatically generate a file with the file name.
is_open()
• You read information from a file into your program using the
stream extraction operator (>>) just as you use that operator
to input information from the keyboard.
Read file
• We can read the data of the entire file by looping and reading
the file. If cin and getline read no content, they will return
false.
Write file
• Input "1 n filename.csv" uses the writing mode. Using random 0~99, 4
numbers are a group of data, n is the number of data to be written. Use
commas to separate the numbers, write Newline after a group.
• Input "2 filename.csv" uses read mode, enter the filename to open the csv
file. Read the grades of each student of four subjects, and output the total
average score of the student in text.
The csv file format is from left to right according to the four subjects of
Chinese, English, Mathematics, and Society. The text format is as follows
file format Output format