Home  >  Article  >  Backend Development  >  How to insert content at a specified location in a file using C++?

How to insert content at a specified location in a file using C++?

WBOY
WBOYOriginal
2024-06-04 15:34:01274browse

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

How to insert content at a specified location in a file using C++?

How to use C++ to insert content at a specified location in a file?

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:

Preparation

First, you need to open the file using the ofstream object:

ofstream file("file_name.txt");

Position the insertion point

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);

Insert content

After positioning the insertion point, you can use the operator to insert content:

file << "要插入的内容";

Practical Case

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn