当前位置:网站首页>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
边栏推荐
- Trial setup and use of idea GoLand development tool
- 深度学习笔记(持续更新中。。。)
- 我的创作纪念日
- SPI mechanism
- stm32F407-------IIC通讯协议
- Button button adaptive size of wechat applet
- The testing process that software testers should know
- Iptables layer 4 forwarding
- 疫情當頭,作為Leader如何進行團隊的管理?| 社區征文
- 微信小程序開發工具 POST net::ERR_PROXY_CONNECTION_FAILED 代理問題
猜你喜欢
可視化yolov5格式數據集(labelme json文件)
Technology sharing | Frida's powerful ability to realize hook functions
[Flutter] dart: class;abstract class;factory;类、抽象类、工厂构造函数
What are MySQL locks and classifications
[shutter] bottom navigation bar implementation (bottomnavigationbar bottom navigation bar | bottomnavigationbaritem navigation bar entry | pageview)
Return a tree structure data
stm32F407-------ADC
Servlet中数据传到JSP页面使用el表达式${}无法显示问题
线程安全的单例模式
通达OA 首页门户工作台
随机推荐
The sandbox explains its vision for the meta universe platform
Deep learning notes (constantly updating...)
Query product cases - page rendering data
Return the only different value (de duplication)
[shutter] hero animation (hero realizes radial animation | hero component createrecttween setting)
awk从入门到入土(2)认识awk内置变量和变量的使用
Depth (penetration) selector:: v-deep/deep/ and > > >
Storage basic operation
Y54. Chapter III kubernetes from introduction to mastery -- ingress (27)
人脸识别6- face_recognition_py-基于OpenCV使用Haar级联与dlib库进行人脸检测及实时跟踪
微信小程序开发工具 POST net::ERR_PROXY_CONNECTION_FAILED 代理问题
Solution for processing overtime orders (Overtime unpaid)
easyExcel
深度学习笔记(持续更新中。。。)
stm32F407-------DMA
When the epidemic comes, how to manage the team as a leader| Community essay solicitation
Recommendation letter of "listing situation" -- courage is the most valuable
require.context
缺少库while loading shared libraries: libisl.so.15: cannot open shared object file: No such file
各国Web3现状与未来