如何从 fstream 中准确读取 128 个字节到字符串对象中?

发布于 2024-09-15 15:01:04 字数 1110 浏览 1 评论 0原文

如何从 fstream 中准确读取 128 个字节到字符串对象中?

我编写了一些代码来读取文件的前 128 个字节并打印它,然后读取文件的最后 128 个字节并打印它。最后一部分有效,因为您可以轻松迭代到 EOF,但如何从前面准确获取 128 个字节?下面的代码不起作用,因为您无法将 128 添加到 ifstream 迭代器,它不可索引,只能递增(看起来)。

当然,我可以创建一个迭代器并 *++ 128 次,但必须有一个简单的行方法来完成它,对吧?

#include <iostream>
#include <fstream>
#include <string>

int main(int argc, char **argv)
{
    std::ifstream ifs ("input.txt",std::ifstream::in | std::ifstream::binary);

    if (ifs.good())
    {
    // read first 128 bytes into a string
        ifs.seekg(0,std::ifstream::beg);
        std::string first128((std::istreambuf_iterator<char>(ifs)),
                             (std::istreambuf_iterator<char>(ifs))+128);

        std::cout << first128 << std::endl;

    // read last 128 bytes into a string
        ifs.seekg(-128,std::ifstream::end);
        std::string last128((std::istreambuf_iterator<char>(ifs)),
                            std::istreambuf_iterator<char>());

        std::cout << last128 << std::endl;

        return 0;
    }

    return 1;
}

How do I read exactly 128 bytes from an fstream into a string object?

I wrote some code to read the first 128 bytes of a file and print it and then the last 128 bytes of the file and print that. The last part works, since you can easily iterate to EOF, but how do I get exactly 128 bytes from the front? The code below doesn't work since you can't add 128 to an ifstream iterator, it's not indexable, only incrementable (it seems).

Sure I could make an iterator and *++ it 128 times, but there must be a single line straightforward way to do it, right?

#include <iostream>
#include <fstream>
#include <string>

int main(int argc, char **argv)
{
    std::ifstream ifs ("input.txt",std::ifstream::in | std::ifstream::binary);

    if (ifs.good())
    {
    // read first 128 bytes into a string
        ifs.seekg(0,std::ifstream::beg);
        std::string first128((std::istreambuf_iterator<char>(ifs)),
                             (std::istreambuf_iterator<char>(ifs))+128);

        std::cout << first128 << std::endl;

    // read last 128 bytes into a string
        ifs.seekg(-128,std::ifstream::end);
        std::string last128((std::istreambuf_iterator<char>(ifs)),
                            std::istreambuf_iterator<char>());

        std::cout << last128 << std::endl;

        return 0;
    }

    return 1;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

ぽ尐不点ル 2024-09-22 15:01:04
char buffer[129];
ifs.read (buffer,128);
buffer[128] = '\0';
first128 = buffer;

那么这个怎么样:

template <typename Itr, typename Out>
void copy_n(Itr it, size_t count, Out out)
{
    for(size_t i=0;i<count;++i)
      out = *it++;
} 

...

std::string first128; 
std::istreambuf_iterator<char> it(ifs);
copy_n( it, 128,
  std::back_inserter<std::string>(first128) );
char buffer[129];
ifs.read (buffer,128);
buffer[128] = '\0';
first128 = buffer;

How about this then:

template <typename Itr, typename Out>
void copy_n(Itr it, size_t count, Out out)
{
    for(size_t i=0;i<count;++i)
      out = *it++;
} 

...

std::string first128; 
std::istreambuf_iterator<char> it(ifs);
copy_n( it, 128,
  std::back_inserter<std::string>(first128) );
如日中天 2024-09-22 15:01:04

我的答案使用中间缓冲区,但也许您会很高兴它使用迭代器从缓冲区初始化字符串。

std::vector<char> buffer(128); // create a buffer
ifs.read( &buffer[0], buffer.size() ); // read to buffer
std::string first128( buffer.begin(), buffer.end() ); // copy from vector

对我来说,他们对 iostream 的实现似乎有点太可爱了。尝试使用迭代器进行流 I/O 过于复杂。

顺便说一句,我怀疑您尝试的实现将在幕后执行各种中间缓冲(可能有些在内核中,有些在库中),以及多次重新分配和复制字符串。成长。

另一个想法:您真的需要标准字符串中的结果吗?您可能只是从向量开始工作——避免了复制到字符串的最后一步。或者,如果您喜欢冒险,您可以创建自己的字符串类,它允许您以与向量相同的方式公开内部缓冲区。

My answer uses an intermediate buffer, but perhaps you will be happy that it uses iterators to initialize the string from the buffer.

std::vector<char> buffer(128); // create a buffer
ifs.read( &buffer[0], buffer.size() ); // read to buffer
std::string first128( buffer.begin(), buffer.end() ); // copy from vector

To me it seems like they got a little too cute with the implementation of iostreams. Trying to use iterators for stream I/O is overly complicated.

By the way, I suspect the implementation that you were attempting will, under the covers, do a variety of intermediate buffering (perhaps some in the kernel, some in the library) as well as re-allocating and copying the string several times as it grows.

One other idea: Do you really need the result in a standard string? You might just work from the vector -- avoiding the final step of copying to a string. Or, if you are feeling adventurous, you could create your own string class that does allow you to expose the internal buffer in the same way that vector does.

踏月而来 2024-09-22 15:01:04

在这里,我对流缓冲区进行了一些研究,通过构造函数直接从 istream 读取字符串:

class mystringbuf : public std::stringbuf
{
public:
    explicit mystringbuf(std::istream& istr, size_t n,
                        std::ios_base::openmode __mode = std::ios_base::in )
    {
        _M_string.resize(n);
        std::stringbuf::_M_stringbuf_init(__mode);
        istr.read(gptr(), n);
    }
public:
    std::stringbuf::char_type* gptr() const
    {
        return std::stringbuf::gptr();
    }
    std::string& str_ref(){
        return _M_string;
    }
};
std::ostream& operator << (std::ostream& ostr, mystringbuf& buf){
    ostr << buf.str_ref();
    return ostr;
}

使用示例:

using std::cout;
using std::endl;

int main()
{
    std::stringbuf buffer;          // empty buffer
    buffer.str("abc def ABC DEF "); // not empty now
    std::istream is (&buffer);      // associate stream buffer to stream
    mystringbuf data(is, 10);       // read 10 bytes
    cout << "data=" <<  data << endl;
    return 0;
}

输出:

data=abc def AB

如果我在某个地方出错,请转发我。

Here i have some of researching over streambuffer, read directly to string from istream by constructor:

class mystringbuf : public std::stringbuf
{
public:
    explicit mystringbuf(std::istream& istr, size_t n,
                        std::ios_base::openmode __mode = std::ios_base::in )
    {
        _M_string.resize(n);
        std::stringbuf::_M_stringbuf_init(__mode);
        istr.read(gptr(), n);
    }
public:
    std::stringbuf::char_type* gptr() const
    {
        return std::stringbuf::gptr();
    }
    std::string& str_ref(){
        return _M_string;
    }
};
std::ostream& operator << (std::ostream& ostr, mystringbuf& buf){
    ostr << buf.str_ref();
    return ostr;
}

Example to use:

using std::cout;
using std::endl;

int main()
{
    std::stringbuf buffer;          // empty buffer
    buffer.str("abc def ABC DEF "); // not empty now
    std::istream is (&buffer);      // associate stream buffer to stream
    mystringbuf data(is, 10);       // read 10 bytes
    cout << "data=" <<  data << endl;
    return 0;
}

Output:

data=abc def AB

Please forward me if i`am somewhere was wrong.

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