Home  >  Q&A  >  body text

c++ - 如何提取一个文本中两行已知内容之间的内容?

请问如何提取一个文本中两行已知内容之间的内容。
比如在某hosts文件中存在如下内容。

……
Localhost (DO NOT REMOVE)
127.0.0.1    localhost
255.255.255.255    broadcasthost
::1    localhost
fe80::1%lo0    localhost
Modified hosts start
……

我想要提取“Localhost (DO NOT REMOVE)”和“Modified hosts start”中的内容到另外一个文本中。
应该怎么解决呢?我使用的如下代码哪里有问题呢?

char str[256],start1[256],end1[256];
    strcpy(start1,"# Localhost (DO NOT REMOVE)");
    strcpy(end1,"# Modified hosts start");
    while (!feof(fstream_backup)){
        fgets(str,1024,fstream_backup);
        if (strcmp(str, start1)==0){
            while (strcmp(str, end1)!=0){
                fgets(str,1024,fstream_backup);
                fprintf(fstream_out,"%s",str);
            }
            
        }
    }

谢谢。

PHPzPHPz2713 days ago509

reply all(2)I'll reply

  • 黄舟

    黄舟2017-04-17 14:02:33

    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
    
    int main()
    {
        bool flag = false;
        ifstream file1("file1.txt");
        ofstream file2("file2.txt");
        string line, des1("Localhost (DO NOT REMOVE)"), des2("Modified hosts start");
        while (getline(file1, line)) {
            if (line == des1) {
                flag = true;
                continue;
            }
            if (line == des2)
                break;
            if (flag)
                file2 << line << endl;
        }
        file1.close();
        file2.close();
    }

    Since it is under C++, it is recommended to write it like this.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 14:02:33

    Why do you need to use such a cumbersome language like c++? The shell can handle it elegantly
    The following statement can output the text between line1 and line5

    cat file1 | sed -n /line1/,/line2/p | sed /line1/d | sed /line2/d > file2

    reply
    0
  • Cancelreply