Home > Article > Backend Development > How to insert content at a specified location in a file using C++?
In C++, use the ofstream class to insert content at a specified location in the file: open the file and locate the insertion point. Insert content using the
In C++, you can use the ofstream
class to insert content at a specified location in a file. Here are the steps on how to do it:
First, you need to open the file using the ofstream
object:
ofstream file("file_name.txt");
Next, you need to locate the place where you want to insert content. This can be achieved in the following ways:
// 定位到文件的偏移量为 offset 的位置 file.seekp(offset, ios::beg);
After positioning the insertion point, you can use the operator to insert content:
file << "要插入的内容";
Suppose there is a file named data.txt
, the content is:
这是一行内容。
You want to insert "new content" into the second line of the file After that, you can do the following:
#include <iostream> #include <fstream> using namespace std; int main() { // 打开文件 ofstream file("data.txt"); // 定位到第二行之后 file.seekp(15, ios::beg); // 15 是第二行开头之前的字节数 // 插入内容 file << "新内容" << endl; return 0; }
After saving and running this program, the contents of data.txt
will become:
这是一行内容。 新内容
The above is the detailed content of How to insert content at a specified location in a file using C++?. For more information, please follow other related articles on the PHP Chinese website!