cout << "Enter the filename " << endl;
    cin >> filename;

    inFile.open(filename);
    int length = 0; 
    while (inFile)
        length++;

    IntStack stack(length);

I keep getting an error and I have no idea why. Can someone explain what is going on with it? After I input the the filename, program terminates. My best guess is that my while loop is wrong or the file is empty...

What do you think is going to change inFile's boolean state to quit the loop?

When the loop returns false or when the file ends or when there is nothing else to check... Right?

The idea is that the loop should end when the file reaches the end. So what will be the condition of the while loop now?

Basically, you're incrementing a variable while inFile is true:

while (inFile)
    length++;

Inside your loop, there's nothing which could possibly change the value of inFile to false, thus the loop will go on forever. Here's some pidgin C, ie it's not correct syntax but should give you the idea:

while(fgetc(file_handle) != EOF)
    length++;

Basically, fgetc will fetch a character from the file. We'll compare it with EOF so that when fgetc reaches the end of the file, our loop will end. Basically, with each iteration of the loop, some action needs to happen which will cause a change, resulting in the condition being broken. I'm not so good at explaining these things very clearly, but I'm sure mike_2000_17 will write a clear answer to this sometime later...

Actually, I just noticed one of your other threads, where someone links to the example code snippet on this page for getting a file's size.

Read the entire file to a string and use string lenght function.
This entirely depends on the size of the file.

Just another way. How ever you can know the file size without reading the file to do the count++;
I would rather not read the file only for its size. very counter productive for serious programe.

Read the entire file to a string and use string lenght function.

That won't necessarily produce the file size because the file may contain characters that are translated by the operating system. For example, MS-Windows uses two bytes to indicate end-of-line and, when read in text mode, those two bytes are converted to only one byte.

Why would you want to wast so much RAM and time to read the file into memory just to get the length of the file, especially when it's soo easy to get the length without reading the file at all?

The only accurate way to get the file size is to use seekp() to the end of the file, then call tellg() to get the byte position as shown in the example linked by Assembly Guy.

Dragon my answer was about not reading the file as they have done. I clearly stated that i will not recommend that. ))

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.