Do you think my program will be able to display the last ten lines of ANY file?

Nov 13, 2014 at 1:16am
So far I've tested my program with the .txt files in my computer and it seems that my program works. But I want to see if YOU can open any .txt file in your computer with this program

Report any bugs please.

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <fstream>

using namespace std;

void displayFile (fstream&);

int main ()
{
    string name;

    cout << "Enter a name of a file" << "\n";
    getline (cin, name);

    fstream file (name.c_str(), ios::in);

    if (file.is_open())
        cout << "File has been opened" << "\n";
    else
        cout << "Error, file cannot be opened" << "\n";


    displayFile (file);

}

void displayFile (fstream& tailFile)
{
    string line1, line2;
    string tail_of_file[1000];
    int byte_position = 0;

    while (getline (tailFile, line1))
        {
        tail_of_file[byte_position] = line1;
        ++byte_position;
        }

    if (byte_position == 10 || byte_position > 10)
        {
        for (int n = (byte_position - 10); n <= (byte_position - 1); n++)
            {
            cout << tail_of_file[n] << "\n";
            }
        }

    else if (byte_position < 10)
        {
        for (int m = 0; m <= (byte_position - 1); m++)
            {
            cout << tail_of_file[m] << "\n";
            }
        }
}

Last edited on Nov 13, 2014 at 1:18am
Nov 13, 2014 at 2:42am
If the file is larger than 1000 lines, then line 35 will overrun the tail_of_file array. At that point the behavior becomes undefined. To see this, try running it with a very large input file and you will probably find that the program crashes.
Nov 13, 2014 at 3:48am
You should check out Circular Buffers ( also called Ring Buffers ). I couldn't find a simple example online, but the general idea is that if you want to see the last ten lines of a file, you make your array of size ten. When you reach the 11th line, you don't need the first element in the array anymore ( the first line ) so you overwrite it:

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
#include <iostream>

int main( void )
{
  const int size = 10;
  std::string lines[size];
  int current = 0;
  bool wrapped = false;

  std::ifstream file( "my_file.txt" );

  std::string temp;
  while ( std::getline( file, temp ) )
  {
    lines[ current++ ] = temp;
    if ( current == size )
    {
      wrapped = true;
      current = 0;
    }
  }

  if ( wrapped )
    for ( int i = current; i < size; ++i ) std::cout << lines[i] << '\n';

  for ( int i = 0; i < current; ++i ) std::cout << lines[i] << '\n';

  return 0;
}
Last edited on Nov 13, 2014 at 3:49am
Topic archived. No new replies allowed.