C++ shared_ptr 并从类中读取
我在从几个对象之间共享文件指针的文件中进行简单读取时遇到问题(它仅适用于简单的 istream,但不适用于我使用 istream 指针的共享指针)。
我试图将整个文件读取到缓冲区(文件本身有几行长。
代码编译,但抛出分段错误。
使用shared_ptr的类:
RecordsSplitter::RecordsSplitter(char *filename):iStream( new ifstream(filename, ifstream::in|ifstream::binary))
{
}
string RecordsSplitter::buildRecord() {
char *buffer;
int buffer_length;
iStream->seekg (0, ios::end)_
buffer_length = iStream->tellg();
cout << buffer_length;
iStream->seekg(0, ios::beg);
iStream->read(buffer,buffer_length);
iStream->close();
cout << buffer;
return 0;
}
int main(int argc, char* argv[]) {
RecordsSplitter *splitter;
splitter = new RecordsSplitter(argv[2]);
int return_num = splitter->buildRecord();
return 0;
}
I have a problem with simple reading from the file that shares file pointer between a few objects (It works for me with just simple istream, but not when I am using shared pointer of istream pointers).
I am trying to read the whole file to the buffer (file itself is a few lines long.
The code compiles, but throws segmentation fault.
The class that uses shared_ptr:
RecordsSplitter::RecordsSplitter(char *filename):iStream( new ifstream(filename, ifstream::in|ifstream::binary))
{
}
string RecordsSplitter::buildRecord() {
char *buffer;
int buffer_length;
iStream->seekg (0, ios::end)_
buffer_length = iStream->tellg();
cout << buffer_length;
iStream->seekg(0, ios::beg);
iStream->read(buffer,buffer_length);
iStream->close();
cout << buffer;
return 0;
}
int main(int argc, char* argv[]) {
RecordsSplitter *splitter;
splitter = new RecordsSplitter(argv[2]);
int return_num = splitter->buildRecord();
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您声明了缓冲区,但没有在任何地方初始化它。
如果您愿意,您需要在
buildRecord
函数中使用它,或者使用 malloc。你的段错误是由这个未初始化的指针引起的,
别忘了清理!
You declare your buffer but you don't initialise it anywhere.
You need this in your
buildRecord
function or a use of malloc if you so desire.Your seg fault is caused by this uninitialised pointer
Don't forget to clean up!