简体   繁体   English

C ++从ifstream读取一块并写入ofstream

[英]c++ read a chunk from ifstream and write to ofstream

I want to read a chunk of bytes from one ifstream then write to another ofstream . 我想从一个ifstream读取一部分字节,然后写入另一个ofstream

here is my code: 这是我的代码:

size_t chunk_size = ...;
std::ifstream ifs(in_file_name);
std::ofstream ofs(out_file_name);

char * buffer = new char[chunk_size];
ifs.read(buffer, chunk_size);
ofs << buffer;
delete[] buffer;

is it the right way to do this? 这是正确的方法吗?

According to CPP document, std::ostream::operator<< accept a streambuffer * as argument. 根据CPP文档, std::ostream::operator<<接受流streambuffer *作为参数。 I'm not sure whether a char array can be treated as a bufferstream. 我不确定是否可以将char数组视为缓冲区流。

(I can compile and run the code, but there is some problem in my program, I'm not sure if it's caused by this, still trying to figure it out...) (我可以编译并运行代码,但是我的程序中存在一些问题,我不确定这是否是由此引起的,仍在尝试找出答案...)

is it the right way to do this? 这是正确的方法吗?

Not quite so. 并非如此。 If you use std::istream::read() then most probably you should pair it with std::ostream::write() and it is better to use std::vector<char> for memory management (or at least smart pointer): 如果您使用std::istream::read()那么很可能应该将其与std::ostream::write()配对,并且最好使用std::vector<char>进行内存管理(或者至少要聪明)指针):

size_t chunk_size = ...;
std::ifstream ifs(in_file_name);
std::ofstream ofs(out_file_name);

{ // you can use block to limit lifetime of the vector
    std::vector<char> buffer( chunk_size );
    ifs.read( buffer.data(), buffer.size() );
    ofs.write( buffer.data(), buffer.size() ); 
} 

problem with your code std::ostream::operator<< overload for const char * expects null terminated string, not binary data of fixed size 代码std::ostream::operator<< const char *重载问题const char *期望以空终止的字符串,而不是固定大小的二进制数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM