Skip to content

Wiki

File operations

About 8 min read

Existing English translations were reused. 7 current source blocks remain in Simplified Chinese, without triggering paid translation.

1.File Operations

Data generated during program execution is temporary data, and it will be released once the program finishes running.

Throughfiles, data can be persisted

C++ File operations require including the header file ==< fstream >==

File types are divided into two categories:

  1. 文本文件 - 文件按照某种字符编码保存文本,例如本教程使用的 UTF-8
  2. 二进制文件 - 文件以文本的二进制形式存储在计算机中,用户一般不能直接读懂它们

Three major categories of file operations:

  1. ofstream: write operations
  2. ifstream: read operations
  3. fstream: read and write operations

1.1.Linux 和 Windows 中的文件路径

本章的 test.txt 这样的相对路径,两种系统都可以使用。需要注意,路径相对于程序运行时的当前工作目录,不一定相对于 .cpp 或 EXE 所在目录。用 VSCode 运行和自己打开终端运行时,工作目录也可能不同。

如果不确定文件生成在哪里,可以先打印:

#include <filesystem>
#include <iostream>

int main()
{
    std::cout << std::filesystem::current_path() << '\n';
    return 0;
}

运行结果: 输出当前工作目录的绝对路径,具体内容以你的电脑为准。

Windows 的反斜杠在普通 C++ 字符串里需要转义,例如 "C:\\work\\test.txt";也可以写原始字符串 R"(C:\work\test.txt)"。入门练习优先使用项目中的相对路径。

本教程源文件和示例文本统一保存为 UTF-8。文本模式下,Windows 与 Linux 的换行处理可能不同;逐字节读写数据时要使用二进制模式。后面的结构体直接读写示例用于理解 read / write,跨平台通信或长期保存数据时,还需要明确字段大小、字节序和数据格式。

1.2.Text file

1.2.1.Write file

The steps to write a file are as follows:

  1. Include header file

    \#include <fstream\>

  2. Create stream object

    ofstream ofs;

  3. Open file

    ofs.open("file path", open mode);

  4. Write data

    ofs << "data to write";

  5. Close file

    ofs.close();

    ​

File open method:

Open mode Explanation
ios::in Open file for reading
ios::out Open file for writing
ios::ate Initial position: end of file
ios::app Append mode for writing to file
ios::trunc If the file exists, delete it first, then create it
ios::binary Binary mode

Note: File opening modes can be used in combination with the | operator.

**For example:** Write a file in binary mode ios::binary | ios:: out

Example:

#include <fstream>

void test01()
{
	ofstream ofs;
	ofs.open("test.txt", ios::out);

	ofs << "姓名:张三" << endl;
	ofs << "性别:男" << endl;
	ofs << "年龄:18" << endl;

	ofs.close();
}

int main() {
    // 程序从 main 函数开始执行,下面的语句会按顺序运行。

	test01();


	// 返回 0 表示程序正常结束。
	return 0;
}

Run result: No output in the terminal; the program will generate in the current directory test.txt, and the file content is:

姓名:张三
性别:男
年龄:18

Summary:

  • File operations must include the header file fstream
  • To read a file, you can use ofstream, or the fstream class
  • When opening a file, you need to specify the path to the file to be operated on, as well as the open mode
  • You can use << to write data to the file
  • After the operation is complete, close the file

1.2.2.Read file

The steps for reading a file are similar to those for writing a file, but there are relatively more reading methods.

The steps to read a file are as follows:

  1. Include header file

    \#include <fstream\>

  2. Create stream object

    ifstream ifs;

  3. Open the file and check whether it was opened successfully

    ifs.open("file path", open mode);

  4. Read data

    Four ways to read

  5. Close the file

    ifs.close();

Example:

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

	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
		return;
	}

	//第一种方式
	//char buf[1024] = { 0 };
	//while (ifs >> buf)
	//{
	//	cout << buf << endl;
	//}

	//第二种
	//char buf[1024] = { 0 };
	//while (ifs.getline(buf,sizeof(buf)))
	//{
	//	cout << buf << endl;
	//}

	//第三种
	//string buf;
	//while (getline(ifs, buf))
	//{
	//	cout << buf << endl;
	//}

	char c;
	while ((c = ifs.get()) != EOF)
	{
		cout << c;
	}

	ifs.close();

}

int main() {

	test01();


	return 0;
}

Running results (the following is an example when entering 10 , 20 , 30 ... in order as prompted; the type size or type name may vary depending on the compiler and platform):

姓名:张三
性别:男
年龄:18

Summary:

  • To read a file, you can use ifstream, or the fstream class
  • The is_open function can be used to determine whether the file was opened successfully
  • close closes the file

1.3.Binary file

Read and write files in binary mode

The opening mode must be specified as ==ios::binary==

1.3.1.Write file

Writing to a file in binary mode mainly uses a stream object to call the member function write.

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

Parameter explanation: The character pointer buffer points to a segment of storage space in memory. len is the number of bytes to read or write.

Example:

#include <fstream>
#include <string>

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

//二进制文件  写文件
void test01()
{
	//1、包含头文件

	//2、创建输出流对象
	ofstream ofs("person.txt", ios::out | ios::binary);
	
	//3、打开文件
	//ofs.open("person.txt", ios::out | ios::binary);

	Person p = {"张三"  , 18};

	//4、写文件
	ofs.write((const char *)&p, sizeof(p));

	//5、关闭文件
	ofs.close();
}

int main() {

	test01();


	return 0;
}

Execution result: The terminal has no output; the program will generate a binary file in the current directory person.txt, into which a 18 object with name "Zhang San" and age Person is written.

Summary:

  • The file output stream object can write data in binary mode through the write function.

1.3.2.Read file

Reading files in binary mode mainly uses a stream object to call the member function read.

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

Parameter explanation: The character pointer buffer points to a segment of storage space in memory. len is the number of bytes to read or write.

Example:

#include <fstream>
#include <string>

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

void test01()
{
	ifstream ifs("person.txt", ios::in | ios::binary);
	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
	}

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

	cout << "姓名: " << p.m_Name << " 年龄: " << p.m_Age << endl;
}

int main() {
    // 程序从 main 函数开始执行,下面的语句会按顺序运行。

	test01();


	// 返回 0 表示程序正常结束。
	return 0;
}

Run result (type size or type name may vary depending on compiler and platform):

姓名: 张三 年龄: 18
  • The file input stream object can read data in binary mode through the read function.