I want to learn how to search in the file by passing the pointer of the stream to a class.
I can successfully get the first character from the file using std::fstream
and std::filebuf*
char symbol;
std::fstream by_fstream;
by_fstream.open("First_test_input.txt");
std::filebuf* input_buffer = by_fstream.rdbuf();
symbol = input_buffer -> sbumpc();
std::cout << "\nSymbol that get from a file by rdbuf(): " << symbol;
Output: Symbol that get from a file by rdbuf(): M
But I'm not sure how can I send any pointer to my original stream of the file from main to a class.
Ideally, it would be great to do something like this:
#include <iostream>
#include <fstream>
class from_file
{
public:
char c;
from_file () {
std::cout << "\nCharacter that get from file by to class variable"
<<" then printed: " << c;
};
from_file (char *pointer){
c = pointer -> sbumpc();
};
~from_file ();
};
int main(){
std::fstream by_fstream;
by_fstream.open("First_test_input.txt");
std::filebuf* input_buffer = by_fstream.rdbuf();
from_file send(&input_buffer);
from_file show;
return 0;
}
Looking for advice on where I can find documentation about similar headers to do a such task.
You are going about this all wrong.
First off, you should pass around (a reference to) the stream itself, not its internal buffer. Use std::istream
methods like read()
or get()
or operator>>
to read from the stream, let it handle it own buffer for you.
Secondly, you are trying to make a 2nd completely separate object "magically" know what a previous object is holding. That is not going to work out the way you want, either.
Try something more like this instead:
#include <iostream>
#include <fstream>
class from_stream
{
public:
char c;
from_stream (std::istream &in){
c = in.get();
// or: in.get(c);
// or: in.read(&c, 1);
// or: in >> c;
};
void show() const {
std::cout << "\nCharacter that get from file by to class variable"
<<" then printed: " << c;
}
};
int main(){
std::ifstream by_ifstream;
by_ifstream.open("First_test_input.txt");
from_stream send(by_ifstream);
send.show();
return 0;
}