代码之家  ›  专栏  ›  技术社区  ›  Museful

让'std::vector<unsigned char>`从'std::string中窃取内存`

  •  0
  • Museful  · 技术社区  · 6 年前

    std::string s 保存原始数据缓冲区,但我们需要 std::vector<uint8_t> v v s

    喜欢什么 std::vector<uint8_t>::vector(std::string&&) 本来可以的,但是从STL的外部做。

    或者,是否有可能 std::stringstream ss 手术的效率和 ss.str()

    1 回复  |  直到 6 年前
        1
  •  0
  •   catnip    6 年前

    好吧,这里有很多评论,让我们试着把一些东西放在一起,因为我需要练习,也许可以获得一些分数[更新:没有:(])。

    我对“现代C++”相当陌生,所以当你找到它时,请接受它。可能需要像C++ 17那样晚,我还没有仔细检查过。任何批评都不受欢迎,但我更愿意编辑我自己的文章。当你读到这篇文章的时候请记住 想做的是从文件中读取他的字节。谢谢。

    更新: stat() 打电话给 fread() 根据@Deduplicator下面的评论。。。随后被替换 fread std::ifstream ,我想我们现在到了。

    #include <string>
    #include <vector>
    #include <optional>
    #include <iostream>
    #include <fstream>
    
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <unistd.h>
    #include <stdio.h>
    #include <errno.h>
    
    using optional_vector_of_char = std::optional <std::vector <char>>;
    
    // Read file into a std::optional <std::vector <char>>.
    // Now handles the file size changing when we're not looking.
    optional_vector_of_char SmarterReadFileIntoVector (std::string filename)
    {
        for ( ; ; )
        {
            struct stat stat_buf;
            int err = stat (filename.c_str (), &stat_buf);
            if (err)
            {
                // handle the error
                return optional_vector_of_char ();   // or maybe throw an exception
            }
    
            size_t filesize = stat_buf.st_size;
    
            std::ifstream fs;
            fs.open (filename, std::ios_base::in | std::ios_base::binary);
            if (!fs.is_open ())
            {
                // handle the error
                return optional_vector_of_char ();
            }
    
            optional_vector_of_char v (filesize + 1);
            std::vector <char>& vecref = v.value ();
            fs.read (vecref.data (), filesize + 1);
    
            if (fs.rdstate () & std::ifstream::failbit)
            {
                // handle the error
                return optional_vector_of_char ();
            }
    
            size_t bytes_read = fs.gcount ();
            if (bytes_read <= filesize)              // file same size or shrunk, this code handles both
            {
                vecref.resize (bytes_read);
                vecref.shrink_to_fit ();
                return v;                            // RVO
            }
    
            // File has grown, go round again
        }
    }    
    
    int main ()
    {
        optional_vector_of_char v = SmarterReadFileIntoVector ("abcde");
        std::cout << std::boolalpha << v.has_value () << std::endl;
    }
    

    Live demo


    阿尔索 :您是否考虑过编写自己的简单容器来映射文件的视图?只是一个想法。