i want to read last line of the file
the name of file is stored in another file.
"output.txt" have lines, the last line of "output.txt" have the name of 2nd file.
#include <iostream>
#include <fstream>
#include <string>
#include <windows.h> //only works in windows not for unix like.
#include <cstdio>
#include <cstdlib> //boolen
#include <math.h> //math f
/////////////////////
usingnamespace std;
ifstream myfile; //open 1st file.
string FLine; //data of file1
ifstream myfile2; //file2
longint FLine1 ; //file data in numaric.
void Start();
void Start1();
/////////////////////? make below lines for availabel for entire program
std::string getLastLine(std::ifstream& in)
{
std::string line;
while (in >> std::ws && std::getline(in, line)) // skip empty lines
;
return line;
}
/////////////////////? make above lines for availabel for entire program
void Start()
{
std::ifstream myfile("output.txt"); //file open
if (myfile.is_open() )
{
std::string line = getLastLine(myfile);
std::cout << line << '\n';
Start1();
}
else
std::cout << "Unable to open file.\n";
Sleep (3000);
Start();
}
/////////////////////
void Start1()
{
// the error is solved by adding "string line;" here but compiled program doesnot work as expected. dont open data file.
myfile2.open (line.c_str() ); //error here
if (myfile2.is_open() )
{
myfile2 >> FLine1 ; //send data to FLine1
cout << "file name " << line << " has " << FLine1 << " value \n" ; //should show data of second file result will be 100.
myfile2.close() ;
Sleep (3000);
}
else std::cout << "unable to open data file. \n";
Start1();
}
/////////////////////
int main(int argc, char** argv)
{
cout << "starting program \n" ;
Sleep (2000);
Start();
return 0;
}
Change line 44: void Start1(const std::string &line)
and line 36: Start1(line);
By the way: line 41 is a recursive call of Start(). It will always be called (not just in the else case like the indention suggests). The same applies to line 56.
Even if it would be called within the else case, it doesn't make sense because the same thing will be done again and again.