C++ foundation – file operation

Time:2022-7-3

File operation (input / output stream)

Overview of file operations

The data generated when the program runs belongs to snack data. Once the program runs, it will be released

adoptfileData can be persisted

Operations on files in c++ include header files(file flow)

There are two types of documents

  • Text file: the file is stored in the computer in the form of ASCII code of text
  • Binary files: files are stored in the computer in binary form of text, and users generally do not read them directly

Three categories of operation documents

  • Ofstream: read file
  • Ifstream: write file
  • Festream: read and write files

text file

Write file

step

  1. Include header file

    #include
  2. Create a flow object

    ofstream ofs;
  3. Open file

    ofs. Open ("file path", opening method);
  4. Write data

    Ofs < < "written data";
  5. Close file

    ofs.cloSe()

Opening mode

  • The file opening method can be used together with|Operator (eg:los:: binary | ios:: in)

route

  • The path is not specified. The default path is the same as that of the current project
  • You can use absolute or relative

example

#include
#Include // add header file
using namespace std;

void test01(){
	ofstream ofs;  // Create a flow object
	ofs. open("test.txt",ios::out);  // Address and method of opening
	Ofs < < Hello < < endl// Contents of the document
	ofs. close();  // Close file
}

int main(int argc, char** argv) {
	test01();
	return 0;
}

read file

There are a little more steps than writing files

step

  1. Include header file

    #include
  2. Create a flow object

    ifstream ifs;
  3. Open the file and judge whether the release is successful

    ifs. Open ("file path", opening method);
    if(!ifs.is_open()){
    		Cout < < file open failed < < endl;
    		return;
    	}else{...}
  4. Read data

    There are four kinds

  5. Close file

    ifs.cloSe()

example

#include
#include
#include
using namespace std;

void test01(){
	ifstream ifs;
	ifs.open("test.txt",ios::in);
	If (! Ifs.is_open()) {// judge whether the opening succeeds
		Cout < < file open failed < < endl;
		return;
	}else{
		//First kind
//	char buf[1024] = {0};
// 		 While (IFS > > buf) {// put the IFS data into buf. When the data is read, false is returned to end the cycle (no data is read)
//			cout << buf <

Little exercise – copy files

On the basis of the above code, test Txt file to test1 Txt file

#Include // add header file
#include
#include

using namespace std; 

void test01(){
	ofstream ofs;    // create object
	ifstream ifs;
    
	ifs. open("test.txt",ios::in);       // Path and method
	ofs.open("test1.txt",ios::out);
    
	If (! Ifs.is_open()) {// copy process
		Cout < < file open failed < < endl// Judge whether it is opened successfully
        return;
	}else{
		string buf;
        
		While (getline (IFS, buf)) {// read the file
			Ofs < < buf < < "(test.txt copied successfully)" < < endl; 	 	 // Write (copy) file
            //Add identification to judge whether the replication is successful
		}
	}
    
	ofs. close();    // Close file
	ifs.close();
}

int main(int argc, char** argv) {
	test01();
	return 0;
}

Binary file

Add an ‘ios:: binary’ when reading and writing files in binary

Write file

Reading files in binary mode mainly uses stream objects to call function write (it doesn’t matter if some of the read data can’t be understood, as long as it can be read back)

Function type: ofs write((const char *) &buffer,int len);

Parameter interpretation: buffer refers to a piece of data in memory; Len is the number of bytes to read

example

#include
#include

using namespace std; 

Class person{// write a class to read
public:
	char m_ Name[64]; // Better use char
	int m_Age;
};

void test01(){
	ofstream ofs("Person.txt",ios::binary | ios::out);  // You can write it in one step
	//ofs.open("Person.txt",ios::binary | ios::out);
    
	Person p = {"Tom" ,18};  // Make an object
     
	ofs. write((const char*)&p,sizeof(p));    // Read it with the write function
	ofs.close();
}

int main(int argc, char** argv) {
	test01();
	return 0;
}

read file

Reading files in binary mode mainly uses stream object to call function read

Function type: ofs read((const char *) &buffer,int len);

Parameter interpretation: buffer refers to a piece of data in memory; Len is the number of bytes to read

example

#Include // it's the same person, 20 years old (class)
#Include // I've written in what I read, so it's more flexible

using namespace std; 

class Person{
public:
	char m_Name[64];
	int m_Age;
};

void test01(){
    //Write file
	ofstream ofs("Person.txt",ios::binary | ios::out);  // You can write it in one step
	//ofs.open("Person.txt",ios::binary | ios::out);
	
	Person p = {"Tom" 20};  // Change the parameter of an object ()
	
	ofs.write((const char*)&p,sizeof(p));    
	ofs.close();
    
	//Read file
	ifstream ifs("Person.txt",ios::binary | ios::in);
    
	if(!(ifs.is_open())){
		Cout < < file open failed < < endl;
		return;
	}else{
		Person p;
		ifs.read((char*)&p,sizeof(p));
		cout << p.m_Name << p.m_Age <

In order to further verify that it is the same file operation, the following inspections can be made

else{
    	Person p = {"Petter",250};// Modify again
		ifs.read((char*) &p,sizeof(p)); 
		cout << p.m_Name << p.m_Age <

Recommended Today

Windows terminal uses nushell+oh-my-posh to beautify

First look at the renderings Please point out if the steps are wrong. Install nushell from github Download from github releaseRelease 0.66.2 · nushell/nushell (github.com) github release download speed may be slow, you can download it hereDownload (serctl.com) Install windows terminal in microsoft store Install oh-my-posh on Microsoft Store Winget can also be used, but […]