Piotr wrote in message
<11**********************@z14g2000cwz.googlegroups .com>...
I have a qestion about reading file in C++.
How can I read a file line by line (i.e. putting a line ends wtih \n in
a string)
[snip code]
Is there a file reading library in c++?
The OP has been answered, but, I thought I'd throw this in and see what y'all
thought of it (..since y'all wrote it (if it looks like something you posted,
you may have)).
// -----------------------------------------------------------------
// Filer.h
// -----------------------------------------------------------------
#ifndef Filer_H
#define Filer_H
// ----------------------------------------------
#include <iostream>
#include <ostream> //std::endl
#include <string>
#include <vector>
// --------------------------------------
#include <stdexcept>
class MyError : public std::runtime_error { public:
MyError(const std::string &msg = "") : std::runtime_error(msg){}
};
// --------------------------------------
class Filer : public std::vector<std::string> {
public:
// Filer(){}
Filer(const char *filename){ Open(filename); }
private: // public: if I use Filer() Ctor, re-use instance, concat files.
void Open(const char *filename) throw(MyError){
std::ifstream in(filename);
if(!in){
throw MyError(__FILE__": Open SonOfABitch!");
} //if(!in)
for( std::string line; std::getline(in, line); ){ // [1]
push_back(line);
} //for()
return;
} //Open(const char*)
public:
void Write(std::ostream& out = std::cout){
if(!out){
throw MyError(__FILE__": Write SonOfABitch!");
} //if(!in)
for(const_iterator w = begin(); w != end(); ++w)
out << *w << std::endl;
return;
} //Write(ostream&)
};
// --------------------------------------
#endif //#ifndef Filer_H
// -----------------------------------------------------------------END
// -----------------------------------------------------------------
// FilerTest.cpp
// -----------------------------------------------------------------
#include <iostream>
#include <ostream> //std::endl
#include "Filer.h"
int main(){
using std::cout;
try{
cout<<"_____ Filer.h _____"<<std::endl;
Filer Afile("Filer.h");
//Filer Afile("ErrFiler.h"); // to test exception.
Afile.Write(cout);
cout<<"Afile.size()="<<Afile.size()<<" lines."<<std::endl;
cout<<"Afile.at(1)="<<Afile.at(1)<<std::endl;
Afile.clear();
cout<<"Afile.size()="<<Afile.size()<<" lines."<<std::endl;
cout<<"_____ Filer.h End _____"<<std::endl;
}
catch(MyError &x){
cout<<"MyError &x.what()="<< x.what() <<std::endl;
} //catch(MyError&)
catch(...){
cout<< "DID NOT CATCH MyError()" <<std::endl;
} //catch(MyError&)
return 0;
} //main()
// -----------------------------------------------------------------END
"Filer.h" is a work-in-progress, so, don't hold back on the crit's. <G>
I've heard it's not a good idea to inherit from std container classes, but,
this seems to work. Good || bad? Was that advice for some other condition?
One objective of "Filer.h" is: KISS!
[1] Andrew Koenig, Walter Brown.
--
Bob R
POVrookie