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

1.5k Views Asked by At

I want to find the last occurrence of a string in a text file of initial size 5MB (might go up to 10MB max) from a fixed specific location (a delimiter) in the same file. I got through finding all occurrences but how to print the last/ final occurrence from a specific location?

Here is my code:

#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;
}

Here is a sample data of my text file:

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
1

There are 1 best solutions below

3
On BEST ANSWER

Assigning your found text to a variable at each iteration will overwrite the variable content and printing it after the loop has ended would print only the last occurence:

Something like this should do :

#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;
}