将数据从std :: istream保存到文件的最佳方法 [英] The best way to save data from std::istream to file

查看:812
本文介绍了将数据从std :: istream保存到文件的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在std::istream中有一些数据,我需要将其保存到磁盘.这是我的草稿:

I have some data in std::istream and I need to save it to the disk. Here is my draft:

    std::istream& i_stream = ReceiveBytes();

    FILE* pFile;
    pFile = fopen("C:\\my_file.exe", "wb");
    char buffer[1024] = {0x0};
    i_stream.read(buffer, 1024);
    std::streamsize n = i_stream.gcount();

    while (n > 0)
    {  
        if (i_stream)
        {
            fwrite(buffer, sizeof(char), sizeof(buffer), pFile);
            i_stream.read(buffer, 1024);
            n = i_stream.gcount();
        }
        else n = 0;
    }

    fclose(pFile);

由于某些原因,我没有保存i_stream中的所有数据,所以在i_stream的末尾丢失了大约50个字节.我在代码中做错了什么?是否有更好的解决方案将数据从std::istream保存到文件?

For some reason I don't save all the data from i_stream, I lose about 50 bytes in the end of the i_stream. What did I do wrong in the code? Is there any better solutions to save data from std::istream to a file ?

推荐答案

CRLF("\ r \ n")输入序列可能会转换为简单的LF("\ n"). fwrite中有一个错误,无论如何,代码都会尝试写入1024个字节. 在打开,写入或关闭输出时没有错误检查.

CRLF ("\r\n") input sequences, might be converted to simple LF ("\n"). There's a bug in the fwrite, the code attempts to write 1024 bytes, no matter what. There's no error checking on the output open, write or close.

更多习惯用法是同时进行一次输入测试:

More idiomatic is to have the input tests once in the while condition :

std::streamsize n;
i_stream.read(buffer, 1024);
while (i_stream || (n = istream.gcount()) != 0) {
    fwrite(buffer, sizeof(char), n, pFile);
    if (n) { i_stream.read(buffer, 1024) };
}

通过混合使用C ++流和C stdio函数,与使用流同时进行读写的代码相比,代码的一致性较差.使用ifstream&来复制二进制文件的代码示例在 http://www.cplusplus.com/reference/ostream/ostream/写/,这可能会有所帮助.

By mixing C++ streams and C stdio functions, the code's less consistent, than if it used streams for both read and write. An example of code to copy a binary file, using ifstream & ofstream is given at http://www.cplusplus.com/reference/ostream/ostream/write/ which might be helpful.

这篇关于将数据从std :: istream保存到文件的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆