当前位置:网站首页>5. File operation
5. File operation
2022-07-03 02:15:00 【I want to go sailing】
The data generated when the program runs are all temporary data , Once the program is finished, it will be released .
Data can be persisted through files
C++ File operations in need to include header files < f s t r e a m > <fstream> <fstream>
There are two file types :
- text file : The document is written in the form of text ASCII The code form is stored in the computer
- Binary : The file is stored in the computer in binary form of text , Users can't read them directly .
There are three categories of operation files :
- ofstream: Write operations
- ifstream: Read operations
- fstream: Read and write operations
5.1 text file
5.1.1 Writing documents
The steps to write a file are as follows :
- Include header file #include < f s t r e a m > <fstream> <fstream>
- Create a flow object ofstream ofs;
- Open file ofs.open(“ File path ”, Open mode );
- Writing data ofs<<“ Written data ”;
- Close file ofs.close();
File open mode :
Open mode | explain |
---|---|
ios::in | Open a file for reading |
ios::out | Open a file for writing |
ios::ate | Initial position : End of document |
ios::app | Write the file by appending |
ios::trunc | If the file exists, delete it first , To create a |
ios::binary | Binary mode |
Be careful : File open mode can be used with , utilize | The operator
for example : Writing files in binary mode :ios::binary | ios::out
#include<iostream>
using namespace std;
#include<fstream> // The header file contains
// text file Writing documents
void test01()
{
// 1. Include header file fstream
// 2. Create a flow object
ofstream ofs;
// 3. Specify how to open
ofs.open("test.txt", ios::out);
// 4. Write content
ofs << " full name : Zhang San " <<endl;
ofs << " Gender : male " <<endl;
ofs << " Age :18" <<endl;
// 5. Close file
ofs.close();
}
int main()
{
test01();
system("pause");
return 0;
}
summary :
- File operations must contain header files fstream
- Reading a file can take advantage of ofstream, perhaps fstream class
- When opening a file, you need to specify the path of the operation file , And how to open it
- utilize << You can write data to a file
- Operation completed , To close the file
5.1.2 Reading documents
Reading a file is similar to writing a file , But there are many ways to read
The steps to read the file are as follows :
- Include header file #include < f s t r e a m > <fstream> <fstream>
- Create a flow object ifstream ifs;
- Open the file and judge whether it is opened successfully ifs.open(“ File path ”, Open mode );
- Reading data Four reading methods
- Close file ifs.close()
Example :
#include<iostream>
using namespace std;
#include<fstream> // The header file contains
#include<string>
// text file Reading documents
void test01()
{
// 1 Include header file
// 2 Create a flow object
ifstream ifs;
// 3 Open file And judge whether it is opened successfully
ifs.open("test.txt", ios::in);
if (!ifs.is_open())
{
cout << " File opening failure " << endl;
return;
}
// 4 Reading data
// The first one is
//char buf[1024] = {0};
//while(ifs>>buf)
//{
// cout << buf <<endl;
//}
// The second kind
//char buf[1024] = {0};
//while (ifs.getline(buf, sizeof(buf)))
//{
// cout << buf << endl;
//}
// The third kind of
//string buf;
//while (getline(ifs, buf))
//{
// cout << buf << endl;
//}
// A fourth
char c;
while((c = ifs.get()) != EOF) // EOF end of file
{
cout << c;
}
// 5 Close file
ifs.close();
}
int main()
{
test01();
system("pause");
return 0;
}
summary :
- Reading a file can take advantage of ifstream, perhaps fstream class
- utilize is_open Function to determine whether the file is opened successfully
- close Close file
5.2 Binary
Read and write files in binary mode
The opening mode should be specified as :ios::binary
5.2.1 Writing documents
Binary file writing mainly uses stream object to call member function write
The function prototype :ostream& write(const char * buffer, int len);
Parameter interpretation : Character pointer buffer Point to a piece of memory .len Is the number of bytes read and written .
Example :
#include<iostream>
using namespace std;
#include<fstream>
// Binary Writing documents
class Person
{
public:
char m_Name[64]; // full name
int m_Age; // Age
};
void test01()
{
// 1 Include header file
// 2 Create a flow object
ofstream ofs;
// 3 Open file
ofs.open("person.txt", ios::out | ios::binary);
// 4 Writing documents
Person p = {
" Zhang San ", 18};
ofs.write((const char *)&p, sizeof(Person));
// 5 Close file
ofs.close();
}
int main() {
test01();
system("pause");
return 0;
}
summary :
File output stream object Can pass write function , Write data in binary mode
5.2.2 Reading documents
Reading files in binary mode mainly uses stream objects to call member functions read
The function prototype :istream& read(char *buffer, int len);
Parameter interpretation : Character pointer buffer Point to a piece of memory .len Is the number of bytes read and written .
Example :
#include<iostream>
using namespace std;
#include<fstream>
class Person
{
public:
char m_Name[64]; // full name
int m_Age; // Age
};
// Binary Reading documents
void test01()
{
// 1 Include header file
// 2 Create a flow object
ifstream ifs;
// 3 Open file Judge whether the file is opened successfully
ifs.open("person.txt", ios::in | ios::binary);
if(!ifs.is_open())
{
cout << " File opening failure " << endl;
return;
}
// 4 Reading documents
Person p;
ifs.read((char *)&p, sizeof(Person));
cout << " full name :" << p.m_Name << " Age : " << p.m_Age << endl;
// 5 Close file
ifs.close();
}
int main() {
test01();
system("pause");
return 0;
}
File input stream object Can pass readh function , Read data in binary mode
边栏推荐
- Redis:Redis的简单使用
- Processing of tree structure data
- 线程安全的单例模式
- Detailed analysis of micro service component sentinel (hystrix)
- Leetcode(540)——有序数组中的单一元素
- Startup mode and scope builder of collaboration in kotlin
- RestCloud ETL 跨库数据聚合运算
- 微信小程序開發工具 POST net::ERR_PROXY_CONNECTION_FAILED 代理問題
- 502 (bad gateway) causes and Solutions
- 【CodeForces】CF1338A - Powered Addition【二进制】
猜你喜欢
His experience in choosing a startup company or a big Internet company may give you some inspiration
Visualisation de l'ensemble de données au format yolov5 (fichier labelme json)
[Flutter] dart: class;abstract class;factory;类、抽象类、工厂构造函数
Hard core observation 547 large neural network may be beginning to become aware?
[camera topic] turn a drive to light up the camera
8 free, HD, copyright free video material download websites are recommended
Machine learning notes (constantly updating...)
Wechat applet Development Tool Post net:: Err Proxy Connexion Problèmes d'agent défectueux
UDP receive queue and multiple initialization test
Y54. Chapter III kubernetes from introduction to mastery -- ingress (27)
随机推荐
In the face of difficult SQL requirements, HQL is not afraid
stm32F407-------ADC
Pytorch convolution network regularization dropblock
Missing library while loading shared libraries: libisl so. 15: cannot open shared object file: No such file
DDL basic operation
The technology boss is ready, and the topic of position C is up to you
Visualisation de l'ensemble de données au format yolov5 (fichier labelme json)
Swift开发学习
Deep learning notes (constantly updating...)
Answers to ten questions about automated testing software testers must see
Prohibited package name
Exception handling in kotlin process
Iptables layer 4 forwarding
[Yu Yue education] reference materials of love psychology of China University of mining and technology
Socket programming
Solution for processing overtime orders (Overtime unpaid)
内存池(内核角度理解new开辟空间的过程)
awk从入门到入土(2)认识awk内置变量和变量的使用
机器学习笔记(持续更新中。。。)
COM和CN