C ++ read () - from socket to stream

Is there a way to read C / C ++ from a socket using read () and have a receive buffer as a file (from a stream) or a similar self-propagating object (vector, for example)?

EDIT: A question arose while I was thinking about how to read a stream socket that can receive the contents of a file, say, 10000+ bytes. I just never wanted to put 20,000 or 50,000 bytes (big enough at the moment) on the stack as a buffer, where the file can be stored temporarily until I can insert it into the file. Why not just transfer it directly to a file to start with it.

How can you get the char * inside the std line: I thought of something like

read( int fd, outFile.front(), std::npos );  // npos = INT_MAX

or something like that.

end edit

Thank.

+5
source share
2

, , - :

template <unsigned BUF_SIZE>
struct Buffer {
    char buf_[BUF_SIZE];
    int len_;
    Buffer () : buf_(), len_(0) {}
    int read (int fd) {
        int r = read(fd, buf_ + len_, BUF_SIZE - len_);
        if (r > 0) len_ += r;
        return r;
    }
    int capacity () const { return BUF_SIZE - len_; }
}

template <unsigned BUF_SIZE>
struct BufferStream {
    typedef std::unique_ptr< Buffer<BUF_SIZE> > BufferPtr;
    std::vector<BufferPtr> stream_;
    BufferStream () : stream_(1, BufferPtr(new Buffer<BUF_SIZE>)) {}
    int read (int fd) {
        if ((*stream_.rbegin())->capacity() == 0)
            stream_.push_back(BufferPtr(new Buffer<BUF_SIZE>));
        return (*stream_.rbegin())->read(fd);
    }
};

, char. read , . , . - :

std::vector<char> input;
char in;
int r;
while ((r = read(fd, &in, 1)) == 1) input.push_back(in);

, . , , , .

, , , , . , , . . :

  • std::list ,
  • API ,
  • readv, BUF_SIZE ( , BUF_SIZE bytes)
+4

All Articles