c++ - 如何提取一个文本中两行已知内容之间的内容?
PHPz
PHPz 2017-04-17 14:00:33
0
2
508

请问如何提取一个文本中两行已知内容之间的内容。
比如在某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);
            }
            
        }
    }

谢谢。

PHPz
PHPz

学习是最好的投资!

全部回覆(2)
黄舟
#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();
}

既然是C++下,建議這樣寫。

Ty80

這樣的需求為什麼要用c++這麼笨重的語言,shell就可以優雅的搞定了
下面語句可以輸出line1和line5之間的文字

cat file1 | sed -n /line1/,/line2/p | sed /line1/d | sed /line2/d > file2
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!