C++ shared_ptr 并从类中读取

发布于 2024-11-27 10:49:42 字数 883 浏览 0 评论 0原文

我在从几个对象之间共享文件指针的文件中进行简单读取时遇到问题(它仅适用于简单的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦幻的心爱 2024-12-04 10:49:42

您声明了缓冲区,但没有在任何地方初始化它。
如果您愿意,您需要在 buildRecord 函数中使用它,或者使用 malloc。

buffer = new char[buffer_length];

你的段错误是由这个未初始化的指针引起的,

别忘了清理!

delete[] buffer;

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.

buffer = new char[buffer_length];

Your seg fault is caused by this uninitialised pointer

Don't forget to clean up!

delete[] buffer;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文