06_file_handling_tutorial
06_file_handling_tutorial
Contents
1 Standard file stream class in C++ 2
1.1 std::fstream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 std::ifstream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 std::ofstream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
4 Practical examples 8
4.1 Text file handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
4.2 Binary file handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
5 Some notes 12
1
Fundamentals of Programming | CSC10012 Department of Knowledge Engineering
• Example usage:
int main () {
std::fstream fs;
return 0;
}
1.2 std::ifstream
• Stream class to read from files.
• Example usage:
int main() {
std::ifstream fin;
// Open the "test.txt" file to read content
// File only contains the line "Hello World"
fin.open("test.txt");
std::string s = "";
std::getline(fin, s); // Read the line "Hello World" from the file into the string s
Page 2 / 12
Fundamentals of Programming | CSC10012 Department of Knowledge Engineering
return 0;
}
1.3 std::ofstream
• Stream class to write on files.
• Example usage:
int main () {
std::ofstream fout;
return 0;
}
• Different stream classes have different ways of calling functions, primarily in the second parameter. Refer to
section 1 for more details.
2.2 close()
• Closes a file.
• Example:
f.close();
Page 3 / 12
Fundamentals of Programming | CSC10012 Department of Knowledge Engineering
2.3 is_open()
• Checks if a file is open.
• Example:
if (!fin.is_open()) {
std::cout << "Error opening file!";
return 0;
}
2.4 eof()
• Checks if eofbit is set.
• Returns true if the stream’s eofbit error state flag is set (which signals that the End-of-File has been reached
by the last input operation), false otherwise.
• Example:
2.5 getline()
• Reads characters from an input stream and places them into a string (std::string).
• To use this function, you must include the <string> header file.
• The following are ways to use the function, assuming the data line to be read is "Name;Age;BirthYear\n":
Page 4 / 12
Fundamentals of Programming | CSC10012 Department of Knowledge Engineering
– A whitespace character (a space ’ ’, tab ’\t’, newline ’\n’...) is found. The whitespace character is
not extracted.
– End of file occurs in the input sequence (this also sets eofbit).
• Example: Reading a 1D array from a file "in.txt" with the following content:
5
1 3 5 7 -1
You only need to use the extraction operator without using std::getline.
...
int arr[100];
int n = 0;
std::ifstream fin("in.txt"); // Open the file to read content
fin.close();
...
• If the file content does not include the number of elements but only the array data (e.g., 1 3 5 7 -1), we
can use a while loop to read the file content.
...
int arr[100];
int n = 0; // In this case, n must be initialized to 0.
std::ifstream fin("in.txt");
fin.close();
...
Note: Avoid combining n++ with ifs >> arr[n]. If the file content ends with a whitespace or newline
character, the combined operation would increment n prematurely, leading to the last element being garbage.
Page 5 / 12
Fundamentals of Programming | CSC10012 Department of Knowledge Engineering
• Example: Square each element of the array read above and write the results to the file "out.txt").
...
std::ofstream fout("out.txt"); // Open the file to write
fout.close();
...
• Example:
std::ifstream fin;
fin.open("data.bin", std::ifstream::binary);
3.3 read()
• Reads/extracts blocks of characters.
• Example: Given a binary file named "data.bin", read the first 4 bytes as the array size. Then, allocate
memory and read the remaining bytes into the array.
...
std::ifstream fin;
fin.open("data.bin", std::ifstream::binary);
int n = 0;
fin.read((char*)&n, (int)sizeof(int));
Page 6 / 12
Fundamentals of Programming | CSC10012 Department of Knowledge Engineering
fin.read((char*)arr, n*sizeof(int));
fin.close();
...
3.4 tellg()
• Returns the input position indicator.
...
std::ifstream fin;
fin.open("data.bin", std::ifstream::binary);
int n = 0;
fin.read((char*)&n, (int)sizeof(int));
std::cout << fin.tellg();
// The console output is 4
...
3.5 seekg()
• Sets the input position indicator.
• Example: Consider a binary file named "data.bin" that solely consists of an integer array. The number of
elements within this array is not explicitly provided.
...
std::ifstream fin;
fin.open("data.bin", std::ifstream::binary);
int n = 0;
fin.seekg(0, std::ifstream::end); // Set the position indicator to the end of file
n = fin.tellg() / sizeof(int); // n now stores the total number of elements in the array
fin.seekg(0, std::ifstream::beg); // Set the position indicator to the beginning of file
...
3.6 write()
• Writes/inserts blocks of characters.
• Example:
...
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Page 7 / 12
Fundamentals of Programming | CSC10012 Department of Knowledge Engineering
fout.write((char*)arr, (int)sizeof(arr));
fout.close();
...
3.7 tellp()
• Returns the output position indicator.
• Example:
...
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
fout.close();
...
3.8 seekp()
• Sets the output position indicator.
• Example:
...
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
fout.close();
...
4 Practical examples
4.1 Text file handling
Problem: Read the data from the file named "data.txt" and store it. The file contains the following information:
Page 8 / 12
Fundamentals of Programming | CSC10012 Department of Knowledge Engineering
Name;Math;Literature
Hoa;9;7
Loan;8;8
Hung;7;8
Thanh;10;9.5
Next, save the student’s name and the total score of their two subjects to a file named "result.txt". The data
should be formatted as follows:
Name;TotalScore
Hoa;16
Loan;16
Hung;15
Thanh;19.5
Solution:
#include <iostream>
#include <fstream> // std::ifstream, std::ofstream
#include <string> // std::getline, std::stof
#include <vector>
struct Student {
string name;
float math, literature;
};
int main() {
// PART 1: READ DATA FROM FILE
// Open the "data.txt" file to read content
ifstream fin;
fin.open("data.txt");
// Declare variables
vector<Student> list_student;
Student temp_student;
string name = "";
Page 9 / 12
Fundamentals of Programming | CSC10012 Department of Knowledge Engineering
// Keep reading until the end of the file is reached or a read operation fails
while (getline(fin, name, ’;’)) {
// The name content is read first to avoid duplicate information
// when there is an empty line at the end of the file
// Read others from the file into temporary variables
getline(fin, math, ’;’);
getline(fin, literature, ’\n’);
//------------------------------------------------------------
// PART 2: SAVE DATA TO FILE
// Open file to save data
ofstream fout;
fout.open("result.txt");
return 0;
}
Page 10 / 12
Fundamentals of Programming | CSC10012 Department of Knowledge Engineering
#include <iostream>
#include <fstream>
#include <cstring>
struct Student {
char id[9];
char lastName[9];
char firstName[10];
};
int main() {
// PART 1: READ DATA FROM FILE
ifstream fin("data.bin", ifstream::binary);
//------------------------------------------------------------
// PART 2: SAVE DATA TO FILE
ofstream fout("result.bin", ofstream::binary);
Page 11 / 12
Fundamentals of Programming | CSC10012 Department of Knowledge Engineering
// Or fout.write((char*)&list[i], (int)sizeof(Student));
}
return 0;
}
5 Some notes
1. When opening a file, it is MANDATORY to close the file.
2. When opening a file for writing (using std::ofstream::out), there are two possible scenarios:
(a) The file does not exist: A new file is created, and the new content is written to it.
(b) The file already exists: The existing content in the file is completely overwritten, and the new content is
written to it.
4. Position the file pointer to the beginning (seekg(0, ifstream::beg)) or end (seekg(0, ifstream::end)).
5. Seek within a binary file using positive offsets from the beginning or negative offsets from the end.
THE END
Page 12 / 12