I have been reading up on this forum looking for answers to my own questions but i find myself stumpped. I basically have to read from a file the last ten lines of input. Yes this is for a homework assignment and i have spent hours on it reading my book and googleing my eyes off. I can open the file, i have found a way to get the total line numbers. I am just totally lost as to how to read the last ten lines only. I have looked into random access but thats in bytes and i dont see how that could work as it should be able to read the last ten lines of any file. Am i missing something? Any help would be greatly appreciated.
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
bool openFile(fstream &);
int getLines(fstream &);
int readLines(fstream &);
char fileName[20];
char * fileNameptr = fileName;
int totalLines = -1;
int main(int argc, char *argv[])
{
fstream dataFile;
if(!openFile(dataFile))
{
cout << "Error opening file...closing" << endl;
return 0;
}
getLines(dataFile);
cout << "Total Lines: " << totalLines << endl;
readLines(dataFile);
system("PAUSE");
return EXIT_SUCCESS;
}
bool openFile(fstream &file)
{
cout << "Please enter the file name" << endl;
cin >> fileName;
file.open(fileNameptr, ios::in);
if(!file)
{
return false;
}
else
{
file.close();
return true;
}
}
int getLines(fstream &file)
{
const int SIZE = 81;
char input[SIZE];
string line [SIZE];
file.open(fileNameptr, ios::in);
if(!file)
{
cout << "Error opening file" << endl;
return 0;
}
file.getline(input, SIZE);
while(!file.eof())
{
totalLines ++;
file.getline(input, SIZE);
}
file.close();
}
int readLines(fstream &file)
{
file.open(fileNameptr, ios::in);
if(!file)
{
cout << "File open error" << endl;
return 0;
}
double numBytes;
char ch;
file.seekg(0L,ios::end);
numBytes = file.tellg();
cout << "The file has " << numBytes << " bytes." << endl;
file.clear();
file.seekg(0L, ios::beg);
file.get(ch);
cout << "ch: " << ch << endl;
}