21xrx.com
2024-09-20 00:42:39 Friday
登录
文章检索 我的文章 写文章
C++如何实现删除文件中的特定行
2023-07-06 04:30:48 深夜i     --     --
C++ 删除 文件 特定行 实现

在C++中实现文件操作是大多数程序员经常需要的一项任务。其中一个常见的任务是删除文件中的特定行。删除行的方法是打开文件,找到要删除的行,然后将其删除。以下是一些实现此任务的方法:

1. 使用C ++ ifstream和ofstream类

C ++ ifstream和ofstream 类是用于在C ++中进行文件输入/输出的常见类。它们可以用来打开文件并在其中查找和删除特定行。以下是一个基本示例代码:


#include <iostream>

#include <fstream>

#include <cstdlib>

using namespace std;

int main()

{

  //打开文件

  ifstream inFile("input.txt");

  ofstream outFile("output.txt");

  //检查文件是否打开

  if (!inFile)

  {

    cerr << "Can't open input file." << endl;

    exit(1);

  }

  //查找并删除特定行

  int lineNumber = 3;

  string line;

  int currentLine = 0;

  while (getline(inFile, line))

  {

    if (currentLine != lineNumber)

    

      outFile << line << endl;

    

    currentLine++;

  }

  //关闭文件

  inFile.close();

  outFile.close();

  //删除原始文件并重命名输出文件

  remove("input.txt");

  rename("output.txt", "input.txt");

  return 0;

}

2. 使用C ++ fstream类

C ++ fstream 类是一个通用类,用于在C ++中进行文件输入/输出。它可以用于打开文件、查找特定行并将其删除。以下是一个基本示例代码:


#include <iostream>

#include <fstream>

#include <cstdlib>

using namespace std;

int main()

{

  //打开文件

  fstream file("input.txt", ios::in|ios::out);

  //检查文件是否打开

  if (!file)

  {

    cerr << "Can't open input file." << endl;

    exit(1);    

  }

  //查找并删除特定行

  int lineNumber = 3;

  string line;

  int currentLine = 0;

  ofstream temp("temp.txt");

  while (getline(file, line))

  {

    if (currentLine != lineNumber - 1)

    

      temp << line << endl;

    

    currentLine++;

  }

  temp.close();

  //删除原始文件并重命名输出文件

  remove("input.txt");

  rename("temp.txt", "input.txt");

  return 0;

}

在上面的示例代码中,可以看到通过创建两个不同的对象来实现查找并删除特定行。首先使用fstream类打开文件,然后使用ofstream类创建一个临时文件,将需要保留的行写入临时文件中。最后,删除原始文件并重命名输出文件。这种方法的好处是不需要在文件中查找特定行,而是直接创建临时文件,只保留需要保留的行。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复