Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/142.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c++;从ifstream中读取一个块,并将其写入ifstream_C++_C++11 - Fatal编程技术网

C++ c++;从ifstream中读取一个块,并将其写入ifstream

C++ c++;从ifstream中读取一个块,并将其写入ifstream,c++,c++11,C++,C++11,我想从一个ifstream中读取一个字节块,然后写入流的另一个 这是我的密码: 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; size\u t c

我想从一个
ifstream
中读取一个字节块,然后写入流的另一个

这是我的密码:

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;
size\u t chunk\u size=。。。;
std::ifstream ifs(在文件名中);
std::ofs流(输出文件名);
char*buffer=新字符[块大小];
读取(缓冲区、块大小);
ofs
这样做对吗

不完全是这样。如果您使用,那么您很可能应该将其与 最好使用
std::vector
进行内存管理(或至少使用智能指针):

size\u t chunk\u size=。。。;
std::ifstream ifs(在文件名中);
std::ofs流(输出文件名);
{//您可以使用块来限制向量的生存期
std::向量缓冲区(块大小);
读取(buffer.data(),buffer.size());
写入(buffer.data(),buffer.size());
} 

代码
std::ostream::operator有问题为什么不直接使用
write
,来写入缓冲区?
char[]
不是
streambuffer*
您可以查看
streambuf
的文档,看看它是否与
char*
远程相关。强烈建议(A)测试
read
调用以确保流仍然有效,以及(b)用于确定之后实际有效的
缓冲区
,并在执行
写入
操作之前执行这两项操作。
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() ); 
}