将指针转到文件缓冲区到类,期望从类中的文件中读取
我想通过将流的指针传递到类中,以了解如何在文件中搜索。
我可以使用std :: fstream
和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;
输出:符号从文件中获取
std :: :Mstd :: fstream
,但我不确定如何将任何指针从主机发送到我的原始文件。
理想情况下,做这样的事情是很棒的:
#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;
}
寻找有关我可以在哪里找到有关类似标题来执行此类任务的文档的建议。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在做错了这一切。
首先,您应该(引用)流本身,而不是其内部缓冲区。使用
std :: istream
例如read> read()
或get()
或operator&gt;&gt;&gt;
从流,让它为您处理自己的缓冲区。其次,您正在尝试“神奇地”使第二个完全单独的对象知道以前的对象所持有的内容。这也不会按照您想要的方式解决。
尝试更多这样的东西:
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 likeread()
orget()
oroperator>>
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: