Contents
  1. I. Text Files
  2. 1.1 Writing to a File
  3. 1.2 Reading a File
  4. II. Binary Files
  5. 2.1 Writing to a File
  6. 2.2 Reading a File

Data generated while a program is running is temporary and is released once the program finishes.

Files can be used to persist data.

File operations in C++ require the #include<fstream> directive.

There are two types of files:

  • Text files: Files are stored on the computer as ASCII text.
  • Binary files: Files are stored on the computer in the binary form of text and generally cannot be read directly by users.

File operations:

  1. ofstream: write operations
  2. ifstream: read operations
  3. fstream: read and write operations

I. Text Files

1.1 Writing to a File

The steps for writing to a file are as follows:

  1. Include the header

    #include<fstream>
  2. Create a stream object

    ofstream ofs;
  3. Open the file

    ofs.open("文件路径", 打开方式)
    Open modeExplanation
    ios::inOpen the file for reading
    ios::outOpen the file for writing
    ios::ateInitial position: end of file
    ios::appWrite to the file in append mode
    ios::truncIf the file exists, delete it before creating it
    ios::binaryBinary mode

    File open modes can be combined using the | operator. For example: ios::binary | ios::out

  4. Write data

    ofs << "写入的数据"
  5. Close the file

    ofs.close

1.2 Reading a File

The steps for reading a file are as follows:

  1. Include the header

    #include<fstream>
  2. Create a stream object

    ifstream ifs;
  3. Open the file and check whether it was opened successfully

    ifs.open("文件路径", 打开方式)
    if(!ifs.is_open()){
        cout << "Error: File open failed." << endl;
        return;
    }
  4. Read data

    string buf;
    while(getline(ifs, buf)){
        cout << buf << endl;
    }
  5. Close the file

    ifs.close();

Example:

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

void test(){
	ifstream ifs;
	ifs.open("test.txt", ios::in);
	if(!ifs.is_open()){
		cout << "Error: File open failed." << endl;
		return;
	}
	string buf;
	while(getline(ifs, buf)){
		cout << buf << endl;
	}
	ifs.close();
}

int main(){
	test();
	system("pause");
	return 0;
}

II. Binary Files

Read from and write to files in binary mode.

The open mode must be specified as ios::binary.

2.1 Writing to a File

Writing to a file in binary mode mainly uses the stream object’s write member function.

Function prototype: ostream& write(const char * buffer, int len);

Parameter explanation: The character pointer buffer points to a region of storage in memory. len is the number of bytes read or written.

//例:将Person类中的数据写入文件
#include<iostream>
#include<fstream>
using namespace std;

class Person{
public:
	char m_Name[64];
	int m_Age;
};

void test(){
	ofstream ofs("person.txt",ios::out | ios::binary);
	Person p = {"Huffie", 21};
	ofs.write((const char *)&p, sizeof(Person));
	ofs.close();
}

int main(){
	test();
	system("pause");
	return 0;
}

2.2 Reading a File

Reading a file in binary mode mainly uses the stream object’s read member function.

Function prototype: istream& read(const char * buffer, int len);

//例:读取文件中的数据
#include<iostream>
#include<fstream>
using namespace std;

class Person{
public:
	char m_Name[64];
	int m_Age;
};

void test(){
	ifstream ifs;
	ifs.open("person.txt",ios::in | ios::binary);
	if(!ifs.is_open()){
		cout << "Error: File open failed." << endl;
		return;
	}
	Person p;
	ifs.read((char *)&p, sizeof(Person));
	cout << "Name:" << p.m_Name << endl;
	cout << "Age: " << p.m_Age << endl;
	ifs.close();
}

int main(){

	test();

	system("pause");
	return 0;
}

Reference: Dark Horse Programmer’s Meticulous Work | C++ Tutorial: Start Programming at 0 and Advance to 1, Making Programming Easier to Learn Link: https://www.bilibili.com/video/BV1et411b73Z