从文件中的特定位置查找文件中字符串的最后一次出现

Find last occurrence of a string in a file from a specific location in that file

本文关键字:文件 最后一次 字符串 定位 位置 查找      更新时间:2023-10-16

我想从同一文件中的固定特定位置(分隔符)查找初始大小为 5MB(最多可能达到 10MB)的文本文件中字符串的最后一次出现。我找到了所有出现的情况,但是如何从特定位置打印最后一次/最后一次出现?

这是我的代码:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
    ifstream file;
    string line;
    char* str = "A-B";
    file.open("test.txt");
    unsigned int currline = 0;
    while(getline(file, line)) {
        currline++;
        if (line.find(str, 0) != string::npos) {
            cout << "found your search term: " << str << " at the " <<"line no.: " << currline << endl;
        }
    }
    return 0;
}

以下是我的文本文件的示例数据:

A,A-B,127.0.0.1
B,B-C,127.0.0.1
# // *From this point I have to search downwards only!*
A-B_1,01-01-15,2,2,L
A-B_2,01-02-15,2,0,L
B-C_1,02-01-16,4,0,L

在每次迭代时将找到的文本分配给变量将覆盖变量内容,并且在循环结束后打印它将仅打印最后一次出现:

像这样的事情应该做:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
    ifstream file;
    string line;
    string found = "Nothing found";
    char* str = "A-B";
    file.open("test.txt");
    unsigned int currline = 0;
    while(getline(file, line)) {
        currline++;
        if (line.find(str, 0) != string::npos) {
            found = line;
        }
    }
    cout << found << endl;
    return 0;
}