Henrique Ferrolho
Henrique Ferrolho

Reputation: 942

Assign last number of a text file to a variable C++

I am doing a program that outputs a list of prime numbers with fstream.

I have this so far:

int export_list (int lim = 50)
{
    int x;
    last_in_txt = ????????????; // assigns last number on txt

    ofstream file ("Primes.txt" , ios::app);

    if (file.is_open()) // if it opens correctly
    {
        for (x = last_in_txt ; x < lim ; x++)
        {
            if (check_prime (x)) // returns 1 when x is prime, returns 0 when not
            {
                file<< x << " ";
            }
        }
        cout << "Done!" << endl << pressenter;
        cin.get();
    }
    else
    {
        cout << "Unable to open file" << endl << pressenter;
        cin.get();
    }
    return(0);
}

So, as you can see, this should append a list of prime numbers to Primes.txt, starting with the prime 1234547.

Primes.txt looks like this:

2 3 5 7 11 13 17 19 23 29 31 37 (...) 1234543 1234547 

My question is how do I assign 1234547 (which is the last number of the txt) to the variable last_in_txt?

Other (not so important) question: Should I save the numbers the way I'm currently doing, or should I store each number in a separate line?

Upvotes: 0

Views: 364

Answers (2)

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70939

My suggestion is that you write using binary format into the text file(using wb in C). In this case you will know how many bytes does the last number occupy and you will be able to use seekg and tellg to get it. If you use plain text format you will have to read char by char from the end and this is more error-prone and also slower.

Upvotes: 1

timrau
timrau

Reputation: 23058

One simple way: keep reading and assign until the whole file is read.

For example,

int last_in_txt = 0;
{
    ifstream infile("Prime.txt");
    int k;
    while(infile >> k) {
        last_in_txt = k;
    }
}
// Now last_in_txt is assigned properly, and Prime.txt is closed

This works well no matter the numbers in Prime.txt are separated by space characters (' ') or by newline characters ('\n').

Upvotes: 2

Related Questions