簡體   English   中英

C ++ - 在文本文件中查找和替換(標准系統庫)

[英]C++ - Find and replace in text file (standard system libraries)

我正在尋找一些建議。

我的情況:

  • 應用程序使用文本本地文件

  • 在文件中某處是這樣的標簽:

      correct =“TEXT” 
    不幸的是,在correct=“TEXT”之間可以有無限的空格。

  • 獲取的文本在功能中進行測試,可以替換(更改必須存儲在文件中 )。

      correct =“CORRECT_TEXT” 

我目前的理論方法:

  • 使用ofstream - 逐行讀取字符串。

  • 查找標記並在字符串中進行更改。

  • 將字符串保存為文件的行。


在C ++中是否有一些簡化方法(使用迭代器?), 使用標准系統庫 (unix)。

謝謝你的想法。

這是一個可能的解決方案,使用:

例:

#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <string>
#include <vector>

struct modified_line
{
    std::string value;
    operator std::string() const { return value; }
};
std::istream& operator>>(std::istream& a_in, modified_line& a_line)
{
    std::string local_line;
    if (std::getline(a_in, local_line))
    {
        // Modify 'local_line' if necessary
        // and then assign to argument.
        //
        a_line.value = local_line;
    }
    return a_in;
}

int main() 
{
    std::ifstream in("file.txt");

    if (in.is_open())
    {
        // Load into a vector, modifying as they are read.
        //
        std::vector<std::string> modified_lines;
        std::copy(std::istream_iterator<modified_line>(in),
                  std::istream_iterator<modified_line>(),
                  std::back_inserter(modified_lines));
        in.close();

        // Overwrite.
        std::ofstream out("file.txt");
        if (out.is_open())
        {
            std::copy(modified_lines.begin(),
                      modified_lines.end(),
                      std::ostream_iterator<std::string>(out, "\n"));
        }
    }

    return 0;
}

我不確定線條的操作應該是什么,但你可以使用:

編輯:

為避免一次將每行存儲在內存中,初始copy()可以更改為寫入備用文件,然后是文件rename()

std::ifstream in("file.txt");
std::ofstream out("file.txt.tmp");

if (in.is_open() && out.open())
{
    std::copy(std::istream_iterator<modified_line>(in),
              std::istream_iterator<modified_line>(),
              std::ostream_iterator<std::string>(out, "\n"));

    // close for rename.
    in.close();
    out.close();

    // #include <cstdio>
    if (0 != std::rename("file.txt.tmp", "file.txt"))
    {
        // Handle failure.
    }
}

您可以將任務拆分成小塊,並弄清楚如何在C ++中執行每個操作:

  • 將文件作為輸入流打開
  • 打開臨時文件作為輸出流
  • 從流中讀取一行
  • 在流中寫一行
  • 將一條線與給定的圖案匹配
  • 替換一行中的文本
  • 重命名文件

注意:在這種情況下,您不需要一次在內存中存儲多行。

它看起來很像'INI文件'語法。 你可以搜索它,你會有很多例子。 但是,實際上很少使用C ++ stdlib。

這是一些建議。 (nb我假設您需要替換的每一行都使用以下語法: <parameter> = "<value_text>"

  • 使用std::string::find方法找到'='字符。
  • 使用std::string::substr方法將字符串拆分為不同的塊。
  • 您需要創建一個修剪算法來刪除字符串前面或后面的每個空白字符。 (可以用std函數完成)

通過所有這些,您將能夠分割字符串並隔離部件以比較它們進行所需的修改。

玩得開心 !

您確定需要在C ++中執行此操作嗎? 既然你在Unix上,你可以調用sed ,它可以通過以下命令輕松完成:

cat oldfile | sed 's/\(correct *= *\)\"TEXT\"/\1\"CORRECT_TEXT\"/' > newfile

如果必須,可以從C ++中調用unix命令(例如,使用<cstdlib> system("command")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM