Read last line from data file

I have this code to read the last line of a data file:


#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>

using namespace std;

bool getLastLine(const char *filename, string &lastLine)
{

#define _LL_BUFFSIZE_ 2048

lastLine.clear(); // regardless, zero out our return string
if (!filename || !*filename) // if no file to work on, return false
return false;

char buff[_LL_BUFFSIZE_]; // our temporary input buffer

ifstream is;
is.open(filename);

if (!is) // return false if couldn't open file
return false;

is.seekg (0, ios::end); // go to end of file
int length = is.tellg(); // find out how large it is
is.seekg(length-min(length,_LL_BUFFSIZE_),ios::beg); // seek back from end a short ways

// read in each line of the file until we're done
buff[0]=0;
do {
// uncomment if you want to skip empty lines or lines that start with whitespace
// fancier logic is probably called for

if (!isspace(buff[0]) && buff[0] != 0)
lastLine = buff;

} while (is.getline(buff, _LL_BUFFSIZE_));

is.close();

return true;
}

//int main (int argc, char * const argv[]) {
void main () {


string lastLine;


if (!getLastLine("data.txt",lastLine))
cout << "Error opening file!" << endl;
else

string lastLine;

const char *pbuff = lastLine.c_str();

// now you can use pbuff like a read-only character array

int i = atoi(pbuff);


printf ("The value read is %d. The double is %d.\n",i,i*2);

// fclose (pFile);

return 0;

}


I've tried to compile it with g++ and returns me the last value of my data file. However, I still have a problem. When I compile it with bcc32, it returns me 0. I don't know why bcc32 doesn't work like g++.
Besides that, I have to open the data file from another computer, using remote desktop, so I need to use fopen function. The name of the other computer is andromeda. If I substitute data.txt by \\andromeda\data.txt in this code, it won't work. Can you help me?

Best Regards,

Paulo Martins
How did you compile the g++ version? Is it a Cygwin or a native Windows app?
Last edited on
Topic archived. No new replies allowed.