Trying to read a specific line of text from a file

I've got a dump file from a mathematical problem that records all tried solutions to a specific formula. Since I will be starting and stopping my program multiple times, but I do not want to lose the tried solutions, I need to access the most recently tried solution (the one at the bottom of the list), but I'm not sure how to do that.

I really don't want to read the entire file, as after a while it may grow to be several gigabytes and that'd be awkward.

getline() and seekg() seem like plausible options, but I can't figure out how to combine them into something usable. Is there anyone who could help me?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main(){
	int startVal[1160];
	char startValChar[1160];
	ifstream valStream;
	valStream.open("solnsdump.txt");
	if (valStream.fail()){
		cout << "No solution dump file found. Starting from 1160x0. \n";
		exit(1);
	}
	bool isFound = false;
	while (!valStream.eof()){
		valStream.seekg(valStream.end - 1161);
	};
}


This is what I have so far, but I don't think it'll work. Any tips would be appreciated.
This should work in practise.
"In theory there is no difference between theory and practice. In practice there is." - Yogi Berra (?)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <fstream>
#include <string>

int main()
{
    const std::streamoff max_line_size_allowance = 2000 ; // adjust as required
    std::string path = "/usr/include/unistd.h" ;
    std::ifstream file( path, std::ios::ate ) ; // open for input, seek to end
    
    if( !file.seekg( -max_line_size_allowance, std::ios::cur ) ) // back by max_line_size_allowance characters 
    {
        // this file has less than max_line_size_allowance characters
        file.clear() ; // clear the error state
        file.seekg(0) ; // and seek to the beginning
    }

    std::string line, last_line ;
    while( std::getline( file, line ) ) last_line = line ;
    std::cout << last_line << '\n' ;
}

http://coliru.stacked-crooked.com/a/2281fc3094b2dc27
http://rextester.com/HXSA54279
Here is a little example to read the last 26 chars from a file.
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
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>

using namespace std;

void main(void)
{
  ifstream src("input.txt");
  if(!src)
  {
    cout << "Error opening file." << endl;
    exit(1);
  }
  src.seekg(-26, ios_base::end);
  if (!src)
  {
    cout << "Error seeking file pos." << endl;
    exit(1);
  }
  cout << "Source pos: " << src.tellg() << endl;
  char ch;
  while(src.get(ch))
    cout << ch;
  cout << "\n\n";
  system("pause");
}


input.txt
1234567890abcdefghijklmnopqrstuvwxyz

Output:
1
2
3
4
Source pos: 10
abcdefghijklmnopqrstuvwxyz

Press any key to continue . . .


Hope you can adopt it to your needs.
Topic archived. No new replies allowed.