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

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

PHPz
PHPzOriginal
2024-06-05 19:31:01278browse

The erase() function in C++ is used to delete content from a file. The syntax is stream.erase(streampos start_pos, streampos end_pos). When using the erase() function, you need to specify the starting position and ending position (byte offset) of the deleted content.

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

How to use the erase() function in C++ to delete content from a file

The C++ library provides a variety of methods to operate File, which includes the erase() function, which allows you to delete a specific range of content from a file.

Syntax:

stream.erase(streampos start_pos, streampos end_pos);
  • stream: File stream object
  • start_pos: To The starting position of the content to be deleted (byte offset)
  • end_pos: The end position of the content to be deleted (byte offset)

Practical case:

Suppose we have a file named "data.txt" that contains the following text:

This is a sample text file.
Hello, world!

To remove "Hello, world!" from the file! " line, you can use the following code:

#include <fstream>
#include <iostream>

using namespace std;

int main() {
  // 打开文件,用于读写
  fstream file("data.txt", ios::in | ios::out);

  if (!file.is_open()) {
    cout << "无法打开文件!" << endl;
    return 1;
  }

  // 定位到要删除内容的起始位置
  file.seekg(16);

  // 定位到要删除内容的结束位置
  file.seekp(27);

  // 删除指定范围的内容
  file.erase(file.tellg(), file.tellp());

  // 关闭文件
  file.close();

  cout << "删除操作成功!" << endl;

  return 0;
}

After running this code, the file "data.txt" will look like this:

This is a sample text file.

The above is the detailed content of How to delete 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