file search

I need to take leftmost variable from last line of file.
getIncrement.seekg( sizeof( ClientData )) gives me last line.
How can i easily reach for leftmost variable in last line, which is id?
Move a cursor to the end of the file, then reverse search for the previous end line. Then read from there.
Edit: My original example code was a brain fart, thank you seeplus. Here's the edit version.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main()
{
        string readVariable;
        ifstream ifile("filePath.txt");
        if(ifile.good())
        {
                ifile.seekg(0, ifile.end);
                int cursor = ifile.tellg();
                cursor -= 2;    // will cause errors if eof is read, could also call ifile.clear() in loop...
                                // easier just to not read eof.
                ifile.seekg(cursor);
                while(readVariable.empty() && cursor > 0)
                {
                        char search = ifile.get();
                        cursor --;
                        ifile.seekg(cursor);
                        search = ifile.get();
                        if(search == '\n')
                        {
                                ifile >> readVariable;
                        }
                }
        }
        ifile.close();
        cout << readVariable << endl;
}
Last edited on
L7 - 8 look suspicious. Decrement cursor and then overwrite it's value?

This will retrieve the last line as a basis for further work:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <fstream>
#include <iostream>
#include <string>

int main() {
	std::ifstream ifile("test.txt");

	if (!ifile)
		return (std::cout << "Cannot open input file\n"), 1;

	std::string lstline;

	ifile.seekg(0, std::ios_base::end);

	do {
		while (ifile.seekg(-1, std::ios_base::cur) && ifile.peek() != '\n');

		std::streampos pos {};

		if (!ifile)
			ifile.clear();
		else {
			pos = ifile.tellg();
			ifile.get();
		}

		std::getline(ifile, lstline);
		ifile.clear();
		ifile.seekg(pos > 0 ? (size_t)pos - 1 : 0);
	} while (lstline.empty());

	std::cout << lstline << '\n';
}

Last edited on
I would be tempted to say to read one letter at a time backwards into a string, reverse the string, and parse the data you wanted off it.
Topic archived. No new replies allowed.