C++ study notes 20-file operation

20.0 Preface

The data generated when the program is running is all temporary data, and will be released once the program finishes running.

Data can be persisted through files .

File operations in C++ need to include the header file - < fstream >.
There are two file types:

  1. Text files - files are stored on your computer as text in ASCII
  2. Binary files - Files are stored on the computer in binary form of text and are generally not directly readable by the user.

Three categories of file operations:

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

20.1 Text files

20.1.1 Writing files

The steps to write a file are as follows:

  1. include header file#include<fstream>
  2. Create a stream objectofstream ofs;
  3. Open the file ofs.open("文件路径,打开方式");, or create the file if it does not exist.
  4. write dataofs<<"写入的数据";
  5. close fileofs.close();

Open method:
insert image description here
Note : The file open method can be used in conjunction with |operators.
For example write a file using binary ios::binary | ios::out.

Example:

#include<iostream>
#include<fstream>  //头文件包含
using namespace std;

//写文件
void test1_01()
{
    
    
	//1.头文件
	//2.创建流对象
	ofstream ofs;    //out file stream
	//3.指定打开方式
	ofs.open("test.txt", ios::out); //如果没有此文件,会默认创建到和源文件相同的文件夹下。
	//4.写内容
	ofs << "姓名:张三" << endl;
	ofs << "性别:男" << endl;
	ofs << "年龄:18" << endl;
	//5.关闭文件
	ofs.close();
}
int main()
{
    
    
	test1_01();
	system("pause");
	return 0;
}

Summarize:

  • File operations must include header files <fstream>.
  • Writing files can utilize ofstreamclasses or fstreamclasses.
  • To open a file, you need to specify the path to operate the file and how to open it.
  • Use <<to write data to the file.
  • When the operation is complete, close the file.

20.1.2 Reading files

The steps to read a file are as follows:

  1. include header file#include<fstream>
  2. Create a stream objectifstream ifs;
  3. Open the file and judge whether the file is opened successfully ifs.open("文件路径,打开方式");.
  4. Read data - four ways.
  5. Close the file ifs.close();.

Four ways:

  1. char buf[1024] = { 0 }; ifs >> buf, read the data in the file into buf in the form of characters, and stop when it encounters a space or a carriage return, and the space or carriage return will not be read. Returns false if end-of-file has been read.
  2. char buf[1024] = { 0 };ifs.getline(buf, sizeof(buf),'\n'), sizeof(buf) indicates the maximum length of the data expected to be read. When the number of data bytes read is equal to this value or the end of the file is read, it will return false; '\n' is a terminator that can be specified. When reading When the specified character is fetched, the reading stops this time, and '\n' can specify to read one line of data each time. (Note: reading stop will not return false)
  3. string buf; getline(ifs, buf,'\n'), the function is similar to 2, but the syntax is different, and stringa header file needs to be added.
  4. char c; (c = ifs.get()), Read the characters in the data in sequence, you need to manually add the termination condition.
#include<iostream>
#include<fstream>
#include<string>
using namespace std;

void read_01()//第一种
{
    
    
	ifstream ifs;
	ifs.open("test.txt", ios::in);
	if (!ifs.is_open())
	{
    
    
		cout << "文件打开失败" << endl;
		return;
	}
	cout << "第一种" << endl;
	
	while (ifs.eof())   //会依次读取,遇到空格或者回车计算一次读取停止,并且当访问到末尾符时结束
	{
    
    
		char buf[1024] = {
    
     0 };
		ifs>>buf;
		cout << buf << endl;
	}

	ifs.close();
}

void read_02()
{
    
    
	ifstream ifs;
	ifs.open("test.txt", ios::in);
	if (!ifs.is_open())
	{
    
    
		cout << "文件打开失败" << endl;
		return;
	}
	cout << "第二种" << endl;
	char buf[1024] = {
    
     0 };
	while(ifs.getline(buf, sizeof(buf),'\n'))//'\n'是指每次读取到回车为止,默认也是回车,如果更改为其他的,会有不同效果。
	{
    
    
		cout << buf << endl;
		//cout << buf;
	}
	
	ifs.close();
}

void read_03()
{
    
    
	ifstream ifs;
	ifs.open("test.txt", ios::in);
	if (!ifs.is_open())
	{
    
    
		cout << "文件打开失败" << endl;
		return;
	}
	cout << "第三种" << endl;
	string buf;
	while(getline(ifs, buf,'\n'))   //getline需要string头文件,功能和第二种差不多,语法不同。
	{
    
    
		cout << buf << endl;
		//cout << buf ;
	}

	ifs.close();
}

void read_04()
{
    
    
	ifstream ifs;
	ifs.open("test.txt", ios::in);
	if (!ifs.is_open())
	{
    
    
		cout << "文件打开失败" << endl;
		return;
	}
	cout << "第四种" << endl;
	char c;
	while ((c = ifs.get()) != EOF)  //end of file,文件尾,这是一个字符一个字符读,并判断当读取到文件尾停止。
	{
    
    
		cout << c ;
	}
	cout << endl;
	
	ifs.close();
}

void test2_01()
{
    
    
	//1.包含头文件
	//2.创建流对象
	//3.打开文件,并且判断是否打开成功
	//4.读数据
	read_01();
	read_02();
	read_03();
	read_04();
	//5.关闭文件
	
}

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

20.2 Binary files

Read and write files in binary mode,

Open with to be specified as ios::binary.

20.2.1 Writing files

Writing files in binary mode mainly uses stream objects to call member functionswrite

Function prototype: ostream& write(const char* buffer , int len);
Parameter explanation: The character pointer bufferpoints to a storage space in the memory, which lenis the number of bytes to read and write.

Example:

#include<iostream>
#include<fstream>  //头文件包含
using namespace std;
class Person
{
    
    
public:
	char m_Name[64]; //姓名 , 用char不用string,char比string底层,string容易出问题.
	int m_Age;
};
void test3_01()
{
    
    
	ofstream ofs("person.txt", ios::binary | ios::out); //可以直接在创建时这样写,省去.open()操作.
	//ofs.open("person.txt", ios::binary | ios::out);
	Person p = {
    
     "张三",18 };  
	ofs.write((const char*)&p, sizeof(Person));  //&p就是地址, ofs传入的是const char*型的指针,所以需要转换类型.
	ofs.close();
	//看起来可能会奇怪,乱码,因为二进制格式,不会影响使用二进制来读。
}
int main3()
{
    
    
	test3_01();
	system("pause");
	return 0;
}

20.2.2 Reading files

Reading files in binary mode mainly uses stream objects to call member functions read.

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

Parameter explanation: The character pointer bufferpoints to a storage space in the memory, which lenis the number of bytes read and written.

Example:

#include<iostream>
#include<fstream>  //头文件包含
using namespace std; 
class Person2
{
    
    
public:
	char m_Name[64];
	int m_Age;
};
ostream& operator<<(ostream& cout,Person2& p)
{
    
    
	cout << "名字:" << p.m_Name << " 年龄:" << p.m_Age << endl;
	return cout;
}
void test4_01()
{
    
    
	ifstream ifs("person.txt", ios::binary | ios::in);
	if (!ifs.is_open())
	{
    
    
		cout << "文件打开失败" << endl;
		return;
	}
	Person2 p;
	ifs.read((char*) &p, sizeof(Person2));
	cout << p << endl;
	ifs.close();
	//文件打开不正常,但是读的内容是正常的,这可能就是二进制文件的特点吧。
}

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

Guess you like

Origin blog.csdn.net/qq_49030008/article/details/123439933