A brief discussion on C++ | Files

 

 Introduction:

The data generated when the program is running is temporary data and will be released once the program is finished running. The data can be persisted through files. File operations in C++ require the inclusion of the header file <fstream>.

C++ provides a wealth of file operation functions. You can use the fstream library in the standard library to perform operations such as reading, writing, and positioning files. File operations are very common in many applications, such as reading configuration files, processing logs, storing data, etc.

First, you need to include the `<fstream>` header file, and then you can create different types of file stream objects, such as ifstream, ofstream and fstream, which are used to read, write and read and write files respectively.

For reading files, you can use the ifstream object. You can open a file for reading by calling the `open()` function and specifying the file name. You can then read data from the file using `>>` and other input operators, or read the file contents line by line using the `getline()` function.

For writing to files, you can use the ofstream object. Likewise, you can open a file for writing by calling the `open()` function and specifying the file name. You can then write the data to the file using `<<` and other output operators.

In addition to reading and writing files, you can also use the fstream object to perform mixed read and write file operations. For example, you can use the `seekg()` and `seekp()` functions to locate the file pointer to perform random read and write operations on the file. The `tellg()` and `tellp()` functions can obtain the current position of the file pointer.

When performing file operations, remember to check whether the file was successfully opened and make sure you close the file when you no longer need to use it. You can use the `is_open()` function to check whether the file was successfully opened and the `close()` function to close the file.

In addition to basic file reading and writing operations, C++ also provides other functions, such as reading and writing binary files, appending files, and file error handling. You can consult the relevant documentation of C++ according to your specific needs to learn and apply these functions in depth.

When performing file operations, you should pay attention to the correctness of the file path to avoid problems where the file cannot be found or cannot be read. In addition, issues such as file locking and concurrent access must be considered when operating files to ensure thread safety and normal release of resources.

In short, the file operation function of C++ is very powerful and flexible, allowing you to easily handle various file operation needs. Proper use of file operations can simplify code, improve efficiency, and facilitate data storage and management.

 

1. Basic knowledge: 

1.1 File Types

There are two types of files:
1. Text files – files are stored in the computer in the form of ASCII code of text.
2 Binary files·Files are stored in the computer in binary form of text, and users generally cannot read them directly.

1.2 Classification of operating files 

 Three major categories of operating files:

1. ifstream: read operation io corresponds to reading and writing

2.ofstream: write operation

3. fstream: read and write operations

1.3 Document steps

1. Include the header file
#include <fstream>

2. Create the stream object
ofstream ofs;

3. Open the file
ofs.open("file path", opening method);

4. Write data
ofs <<"written data";

5. Close the file
ofs.close();

1.4 File opening method

ios.in Open file for reading
ios:out Open file for writing
ios:.ate Initial position: end of file
ios:.app Write file in append mode
ios::trunk If the file exists, delete it first and then create it.
ios::binary binary mode

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

 Write file code example:

#include <iostream>
#include <fstream>
using namespace std;
void fun() {
	//1.头文件
	//2.创建流对象
	fstream ofs;
	//3.指定打开方式
	ofs.open("test.txt", ios::out);
	//4.写内容
	ofs << "姓名:张三" << endl;
	ofs << "性别:男" << endl;
	//5.关闭文件
	ofs.close();
}
int main() {
	fun();
	return 0;
}

You can use ofstream or fstream to write files 

Reading file code example:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void fun() {
	//1.头文件
	//2.创建流对象
	fstream ofs;
	//3.指定打开方式
	ofs.open("test.txt", ios::out);
	//4.写内容
	ofs << "姓名:张三" << endl;
	ofs << "性别:男" << endl;
	//5.关闭文件
	ofs.close();
}

void fun1() {
	ifstream ofs;
	ofs.open("test.txt", ios::in);
	//ofs.is_open()打开失败返回false
	if (!ofs.is_open()) {
		cout << "文件打开失败" << endl;
	}
	//读数据
	// 
	//第一种
	char buf[1024] = { 0 };
	//ofs按行输入到buf中,每次循环覆盖上一次
	while (ofs >> buf) {
		cout << buf << endl;
	}

	//第二种
	char buf1[1024] = { 0 };
	//和第一种一样,限定最大的大小
	while(ofs.getline(buf1, sizeof(buf1)) ){
		cout << buf1 << endl;
	}
	//第三种
	string buf2;
	//从ofs输入到buf2中
	while (getline(ofs, buf2)) {
		cout << buf2 << endl;
	}

	//第四种,不推荐
	char c;
	while ((c=ofs.get())!=EOF) {
		cout << c;
	}
	ofs.close();
}
int main() {
	fun();
	fun1();
	return 0;
}

Summary:
·To read files, you can use ifstream or fstream class

·Use the is_open function to determine whether the file is opened successfully.

.closeClose the file

2. Binary reading and writing

Code example:

#include <iostream>
//1.头文件
#include <fstream>
using namespace std;
class person {
public:
	int age;
	const char *name;    //C++要加const,学到了
};

void fun() {
	//2.打开数据流(读写模式)
	fstream ofs;
	//3.打开文件
	ofs.open("erjinzhi.txt", ios::out | ios::binary);
	//4.写数据
	person p;
	p.age = 18;
	p.name = "tom";
	ofs.write((const char*)&p,sizeof(person));
	p.age = 19;
	p.name = "tony";
	ofs.write((const char*)&p, sizeof(person));
	//5.关闭文件
	ofs.close();
}

void read() {
	//2.打开数据流模式
	fstream ofs;
	//3.打开文件
	ofs.open("erjinzhi.txt", ios::in | ios::binary);
	if (!ofs.is_open()) {
		cout << "打开失败" << endl;
	}
	//4.读数据
	person p;
	ofs.read((char*)&p, sizeof(p));
	cout << p.age << endl;
	cout << p.name << endl;
	ofs.read((char*)&p, sizeof(p));
	cout << p.age << endl;
	cout << p.name << endl;
	ofs.close();
}
int main() {
	fun();  //写文件
	read();
	return 0;
}

ofs.write((const char*)&p,sizeof(person));

ofs.open("erjinzhi.txt", ios::in | ios::binary);

Just pay attention to the usage of these two functions

Guess you like

Origin blog.csdn.net/m0_73731708/article/details/132927585
Recommended