C++ file I/O operation (text file, binary file)


0 File I/O operations

The data generated when the program is running are all temporary data , and the temporary data will be released when the program is executed. accessiblefilePersist data .

Note: in C++Operating fileAt the time, header files related to the file stream must be included <fstream>.


Document classification :
(1) 文本文件: Documents in textASCII codeStored in the form;
(2) 二进制文件: the file is in textBinaryStored in form, users generally cannot read it directly.


Types of file operations :
(1) ofstream: Write operation (Output File Stream)
(2) ifstream: Read operation (Input File Stream)
(3) fstream:Read/write operation(File Stream)


1 text file

1.1 Writing files

Steps to write a file :
(1) Include the header file : #include <fstream>
(2) Create an output stream object : ofstream ofs;(Create a file output stream object)
(3) UseSpecify path and methodOpen the file : ofs.open("文件路径", 打开方式);
(4) Output stream objects and 左移运算符<<write data through the file : ofs << "写入数据";
(5) Close the file :ofs.close();

Note: Through ofstreamthe constructor of the file output stream class , specify the path and opening method of the file when creating the file output stream object , thereby omitting the ofs.open("文件路径", 打开方式);function:
ofstream ofs("文件路径", 打开方式);

File opening method :

Open method Explanation
ios::in Read file
ios::out Write file
ios::ate Initial position of opening: end of file
ios::app Write files in append mode ( append write )
ios::trunc If the file already exists, delete it and then create it
ios::binary Binary way

Note: The file opening method can be used in |combination with bit or operator .
Example: write files in binary mode: ios::binary | ios:: out.


Text file-write operation summary :
(1) File operations must include header files <fstream>;
(2) Write files can use ofstreamor fstreamclasses;
(3) When opening files, you need to specify the file path and opening method ;
(4) File output streams can be used Object and write data左移运算符<< to the file ; (5) After the operation is completed, the file needs to be closed .


Example : text file-write operation

#include <iostream>
using namespace std;
#include <fstream>	//1.包含文件流相关的头文件

void writeTextFile() {
    
    
	//2.创建文件输出流对象
	ofstream ofs;

	//3.以指定方式打开
	ofs.open("test.txt",ios::out);

	//4.写内容
	ofs << "姓名:Tom" << endl;
	ofs << "时间:2021年2月14日" << endl;

	//5.关闭文件流对象
	ofs.close();
}

int main() {
    
    
	writeTextFile();

	return 0;
}

1.2 Read files

Steps to read the file :
(1) Include the header file : #include <fstream>
(2) Create an input stream object : ifstream ifs;(Create a file input stream object)
(3) UseSpecify path and methodOpen the file and determine whether the file is opened successfully :
Open the file: ifs.open("文件路径", 打开方式);
Determine whether the file is opened successfully: ifs.is_open()
(4) Input the stream object through the file , and read the data in 4 ways :

①Character array and右移运算符>>

char buffer[1024] = {
    
    0};	//初始化字符数组
while(ifs >> buffer){
    
    
	cout << buffer << endl;
}

array of characters and member functions ifstream classifstream& getline(char *_Str, std::streamsize _Count)
ifstream :: getline (char array buffer, the buffer size)

char buffer[1024] = {
    
     0 };	//初始化字符数组
while (ifs.getline(buffer, sizeof(buffer))) {
    
    
	cout << buffer << endl;
}

string and global functiongetline(istream &_istr, string &_str)
getline (input stream objects, string)

string str;
while(getline(ifs, str)){
    
    
	cout << str << endl;
}

④Read character by character , member functions of the ifstream classget() and 文件结束符EOF(end of file) [not recommended]

Note: The efficiency of character-by-character reading is low, so it is not recommended.

char ch;
while ((ch = ifs.get()) != EOF) {
    
    
	cout << ch;
}

(5) Close the file :ifs.close();


Determine whether the content of the text file is empty (the file exists):
Read 1 character of the text file and judge whether the character is EOF mark.
(1) Create a file input stream object : ifstream ifs;
(2) Read a text file1 character: char ch; ifs >> ch;Or ch = ifs.get();
(3) Determine whether the currently read character has reached the end of the file (ie 文件结束符EOF):
①Use the member function of the file input stream class ; ② Determine whether the current character is .bool ifstream::eof();
文件结束符EOF

Example : Determine whether the content of a text file is empty

//方式1:文件输入流对象调用成员函数ifs.eof()
ifstream ifs(FILENAME, ios::in);
char ch;
ifs >> ch;
if(ifs.eof()){
    
    
	cout << "文本文件内容为空..." << endl;
}

//方式2:判断当前字符是否为EOF文件结束符
ifstream ifs(FILENAME, ios::in);
char ch;
if((ch = ifs.get()) == EOF){
    
    
	cout << "文本文件内容为空..." << endl;
}

Text file-read operation summary :
(1) The file operation must include the header file <fstream>;
(2) The ifstreamor fstreamclass can be used to write the file ;
(3) After the is_open()file is opened , the ifstream class function should be used to determine whether the file is opened successfully;
(4) After the operation is completed, the file needs to be closed .


Example : text file-read operation

#include <iostream>
using namespace std;
#include <fstream>	//1.包含文件流相关的头文件
#include <string>

void readTextFile() {
    
    
	//2.创建文件输入流对象
	ifstream ifs;

	//3.打开文件,并判断是否打开成功
	ifs.open("test.txt", ios::in);
	if (!ifs.is_open()) {
    
    
		cout << "文件打开失败" << endl;
		return;
	}

	//4.读数据
	//第1种:字符数组和右移运算符>>
	//char buffer[1024] = { 0 };	//初始化字符数组
	//while (ifs >> buffer) {
    
    
	//	cout << buffer << endl;
	//}

	//第2种:字符数组和istream类成员函数getline()
	//char buffer[1024] = { 0 };	//初始化字符数组
	//while (ifs.getline(buffer, sizeof(buffer))) {
    
    
	//	cout << buffer << endl;
	//}

	//第3种:字符串和全局函数getline()
	string str;
	while(getline(ifs, str)){
    
    
		cout << str << endl;
	}

	//第4种:按字符读取和EOF文件尾标志(end of file)【不建议】
	//char ch;
	//while ((ch = ifs.get()) != EOF) {
    
    
	//	cout << ch;
	//}

	//5.关闭文件
	ifs.close();
}

int main() {
    
    
	readTextFile();

	return 0;
}

2 Binary files

The file is read and written in binary mode, open()函数and the opening method in the file needs to be used additionally ios::binary.


2.1 Writing files

Write files in binary mode, passFile output stream objectofstream ofs;Call member functionwrite() .
Function prototype : ostream& write(const char* buffer, int len);
Parameter explanation : bufferthe memory address pointed to by the character pointer ; it lenis the number of bytes read and written.

Note 1: When writing files in binary mode, writing is supportedCustom data type, The address of the custom data type object (for example Object *)Forced transferIs the const char *type.
Example: ofs.write((const char*) &obj, sizeof(obj));
Note 2: For files with binary write operations, the content may be displayed as garbled characters , and binary read operations need to be used for analysis.
Note 3: Through ofstreamthe constructor of the file output stream class , specify the path and opening method of the file when creating the file output stream object , thereby omitting the ofs.open("文件路径", 打开方式);function:
ofstream ofs("文件路径", 打开方式);

Example : Write custom data type in binary mode

#include <iostream>
using namespace std;
#include <fstream>	//1.包含文件流相关的头文件

//自定义数据类型
class Student{
    
    
public:
	char name[32];
	int score;
};

int main() {
    
    
	/*
	//2.创建文件输出流对象
	ofstream ofs;

	
	//3.以二进制方式打开文件,并执行写操作
	ofs.open("student.txt", ios::binary | ios::out);
	*/
	
	//简化写法
	/* 通过输出流类ofstream的构造函数,创建对象时指定文件路径及打开方式 */
	ofstream ofs("student.txt", ios::binary | ios::out);

	//4.写文件
	Student stu = {
    
    "Tom", 99 };
	//将自定义的数据类型指针,强转为const char*
	ofs.write((const char*)&stu, sizeof(stu));

	//5.关闭文件
	ofs.close();

	return 0;
}

2.2 Read files

Read the file in binary mode, passFile input stream objectifstream ifs;Call member functionread() .
Function prototype : istream& read(char* buffer, int len);
Parameter explanation : bufferthe memory address pointed to by the character pointer ; it lenis the number of bytes read and written.

Note 1: When reading a file in binary mode , it supports readingCustom data type, The address of the custom data type object (for example Object *)Forced transferIs the char *type.
Example: ifs.read((char*) &obj, sizeof(obj));
Note 2: After opening the file, you should use the is_open()function of the ifstream class to determine whether the file is opened successfully.

Example : Read custom data type in binary mode

#include <iostream>
using namespace std;
#include <fstream>	//1.包含文件流相关的头文件

//自定义数据类型
class Student {
    
    
public:
	char name[32];
	int score;
};

int main() {
    
    
	/*
	//2.创建输入流对象
	ifstream ifs;

	//3.打开文件并判断是否打开成功
	ifs.open("student.txt", ios::binary | ios::in);
	*/

	//简化写法
	/* 通过输出流类ofstream的构造函数,创建对象时指定文件路径及打开方式 */
	ifstream ifs("student.txt", ios::binary | ios::in);

	if (!ifs.is_open()) {
    
    
		cout << "文件打开失败..." << endl;
		return 0;
	}

	//4.读文件
	Student stu;
	ifs.read((char*)&stu, sizeof(stu));
	cout << "姓名:" << stu.name << endl;
	cout << "成绩:" << stu.score << endl;

	//5.关闭文件
	ifs.close();

	return 0;
}

Guess you like

Origin blog.csdn.net/newson92/article/details/113778179