[C + +] learning notes [13]

File operation

The data generated when the program runs belongs to temporary data. Once the program is run, these temporary data will be released. At this time, we can persist the data through files.

File operations in C + + need to include header files < fstream

There are two types of files:

  • Text file: the file is stored in the computer in the form of ASCII code of text
  • Binary files: files are stored in the computer in binary form of text, and users generally can't read them directly

Three categories of operation documents:

  • ofstream: write operation
  • ifstream: read operation
  • fstream: read / write operation

1, Text file

Write file

The steps for writing files are as follows:

  • Include header file: #include < fstream >
  • Create a stream object: ofstream ofs;
  • Open file: ofs Open ("file path", opening method);
  • Write data: ofs < < "written data";
  • Close file: ofs close();

File opening method

Open modeexplain
ios::inOpen file for reading
ios::outOpen file for writing
ios::ateInitial location: end of file
ios::appWrite file in append mode
ios::truncIf the file exists, delete it before creating it
ios::binaryBinary mode

Note: the file opening method can be used in conjunction with the | operator
For example, write the file ios::binary | ios::out in binary mode

Write code below to practice writing files

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

void test01()
{
	//Create flow object
	ofstream ofs;

	//Specify the opening method. If no explicit file path is specified, the text file will be created to the same path as the project
	ofs.open("text.txt", ios::out);

	//Write data
	ofs << "Name: Zhang San" << endl;
	ofs << "Gender: Male" << endl;
	ofs << "Age: 19" << endl;

	//Close file
	ofs.close();
}

int main()
{
	test01();
	return 0;
}

First, after we run the program, then right-click main CPP select the path where the open file is located:


Next, we can see a text file in the path where the project is located


After opening the file, there will be three lines of data entered in our program

read file

Reading a file is similar to writing a file, but there are many reading methods.

The steps for reading files are as follows:

  • Include file: # >
  • Create a stream object: ifstream ifs;
  • Open the file and judge whether the file is opened successfully: ifs Open ("file path", opening method);
  • Read data: four ways to read
  • Close file: ifs close();

The case code for reading the file is as follows:

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

void test02()
{
	//Create flow object
	ifstream ifs;

	//Open the file and judge whether the file is opened successfully
	ifs.open("text.txt", ios::in);
	if (!ifs.is_open())
	{
		cout << "File open failed" << endl;
		return;
	}

	//The fourth method is to read data, but this method is not recommended. It will be very slow to read data one character at a time
	char c;
	while ((c = ifs.get()) != EOF)//EOF===end of file
	{
		cout << c;
	}

	The third way to read data
	//string buf;
	//while (getline(ifs, buf))
	//{
	//	cout << buf << endl;
	//}

	The second way to read data:
	//char buf[1024] = { 0 };
	//while (ifs.getline(buf, sizeof(buf)))
	//{
	//	cout << buf << endl;
	//}

	Read data
	The first way:
	//char buf[1024] = { 0 };
	//while (ifs >> buf)
	//{
	//	cout << buf << endl;
	//}

	//Close file
	ifs.close();
}

int main()
{
	test02();
	return 0;
}

Note that what we read here is the text file written in the previous case.


2, Binary file

Read and write files in binary mode. The opening mode should be specified as ios::binary

Write file

  • Binary file writing mainly uses the stream object to call the member function write
  • Function prototype: ostream & write (const char * buffer, int len);
  • Parameter interpretation: the character pointer buffer points to a storage space in memory, and len is the number of bytes read and written

The example code is as follows:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class Person
{
public:
	char m_name[64];
	int m_age;

};

void test01()
{
	ofstream ofs;
	ofs.open("person.txt", ios::out | ios::binary);

	//You can combine the above two steps into one
	//ofstream ofs("person.txt", ios::out | ios::binary);

	Person p = { "Zhang San",19 };
	ofs.write((const char*)&p, sizeof(Person));

	ofs.close();
}

int main()
{
	test01();

	system("pause");
	return 0;
}

Open the folder where the file is located to see a person file:

When you open the file, the following occurs:

read file

  • Binary file reading mainly uses the stream object to call the member function read
  • Function prototype: istream & read (char * buffer, int len);
  • Parameter interpretation: the character pointer buffer points to a storage space in memory, and len is the number of bytes read and written

The example code is as follows:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class Person
{
public:
	char m_name[64];//full name
	int m_age;//Age

};

void test02()
{
	ifstream ifs;
	ifs.open("person.txt", ios::in | ios::binary);

	if (!ifs.is_open())
	{
		cout << "File open failed" << endl;
	}

	Person p;
	ifs.read((char*)&p, sizeof(Person));
	cout << "full name:" << p.m_name << " " << "Age:" << p.m_age << endl;

	ifs.close();
}

int main()
{
	test02();

	system("pause");
	return 0;
}

From the following results, we can see that we will use person Txt read out:


💖💖💖
2022 Chapter 1!!!
come on.

Keywords: C++ Back-end

Added by ntnwwnet on Wed, 05 Jan 2022 01:21:36 +0200