C/C + + memo: file operation (reading and writing files)

Posted by JohnResig on Mon, 14 Feb 2022 15:31:21 +0100

File operation

  • The data generated when the program runs belongs to temporary data. Once the program runs, it will be released
  • Data can be persisted through files
  • File operations in C + + need to include header files < fstream >

There are two types of files:

  1. Text file - the file is stored in the computer as ASCII code of text
  2. Binary files - files are stored in the computer in binary form of text, and users generally can't read them directly

There are three categories of operation documents:

  1. ofstream: write operation
  2. ifstream: read operation
  3. fstream: read / write operation

1. Text file

1.1 writing documents

The steps for writing files are as follows:

  1. Include header file

    #include <fstream>

  2. Create flow object

    ofstream ofs;

  3. Open file

    ofs. File opening mode ("open");

  4. Write data

    Ofs < < "written data";

  5. Close file

    ofs.close();

File opening method:

Open modeexplain
ios::inOpen file for reading
ios::outOpen file for writing
ios::ateInitial location: end of file
ios::appWrite file in append mode
ios::truncIf the file exists, delete it before creating it
ios::binaryBinary mode

Note: the file opening method can be used in conjunction with the | operator

For example: write the file ios::binary | ios:: out in binary mode

Example:

#include <fstream> 					// Header file

void test(){
	ofstream ofs;					//Create flow object
	ofs.open("test.txt", ios::out);	//Open file

	ofs << "Name: Zhang San" << endl;		//Write data
	ofs << "Gender: Male" << endl;
	ofs << "Age: 18" << endl;

	ofs.close();					//Close file
}

1.2 document reading

The steps of reading files are as follows:

  1. Include header file

    #include <fstream>

  2. Create flow object

    ifstream ifs;

  3. Open the file and judge whether the file is opened successfully

    ifs.open("file path", opening method);

  4. Read data

    Four ways to read

  5. Close file

    ifs.close();
    Example:

#include <fstream>
void test(){
	ifstream ifs;
	ifs.open("test.txt", ios::in);

	if (!ifs.is_open())					//Judge whether the file is opened successfully
	{
		cout << "File open failed" << endl;
		return;
	}

	//The first way
	char buf[1024] = { 0 };
	while (ifs >> buf){		
		cout << buf << endl;
	}

	//Second
	char buf[1024] = { 0 };
	while (ifs.getline(buf,sizeof(buf))){	//sizeof(buf) is the maximum number of saves
		cout << buf << endl;
	}

	//Third
	string buf;
	while (getline(ifs, buf)){
		cout << buf << endl;
	}
	
	//Fourth
	char c;
	while ((c = ifs.get()) != EOF){
		cout << c;
	}

	ifs.close();
}

2 binary files

Read and write files in binary mode

The opening method should be specified as ios::binary

2.1 writing documents

Writing files in binary mode mainly uses the stream object to call the member function write

Function prototype: ostream & write (const char * buffer, int len);

Parameter interpretation: the character pointer buffer points to a storage space in memory. len is the number of bytes read and written

Example:

#include <fstream>

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

//Binary file write file
void test()
{
	//1. Include header file

	//2. Create output stream object
	ofstream ofs("person.txt", ios::out | ios::binary);	//2. 3 merge into one step
	
	//3. Open file
	//ofs.open("person.txt", ios::out | ios::binary);

	Person p = {"Zhang San"  , 18};

	//4. Write file
	ofs.write((const char *)&p, sizeof(p));

	//5. Close file
	ofs.close();
}

2.2 reading documents

Binary file reading mainly uses the stream object to call the member function read

Function prototype: istream & read (char * buffer, int len);

Parameter interpretation: the character pointer buffer points to a storage space in memory. len is the number of bytes read and written

Example:

#include <fstream>

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

void test()
{
	ifstream ifs("person.txt", ios::in | ios::binary);
	if (!ifs.is_open())			//Judge whether the file is opened successfully
	{
		cout << "File open failed" << endl;
		return;
	}

	Person p;
	ifs.read((char *)&p, sizeof(p));

	cout << "full name: " << p.m_Name << " Age: " << p.m_Age << endl;
}
  • The file input stream object can read data in binary mode through the read function

Topics: C C++