C++ 复制文件。数据不足

标签 c++ file copy

我正在尝试复制文件,但无论我尝试什么,拷贝似乎都少了几个字节。

_file 是一个设置为二进制模式的 ifstream。

void FileProcessor::send()
{
    //If no file is opened return
    if(!_file.is_open()) return;
    //Reset position to beginning
    _file.seekg(0, ios::beg);

    //Result buffer
    char * buffer;
    char * partBytes = new char[_bufferSize];
    //Packet *p;
    //Read the file and send it over the network

    while(_file.read(partBytes,_bufferSize))
    {
        //buffer = Packet::create(Packet::FILE,std::string(partBytes));
        //p = Packet::create(buffer);
        //cout<< p->getLength() << "\n";
        //writeToFile(p->getData().c_str(),p->getLength());
        writeToFile(partBytes,_bufferSize);
        //delete[] buffer;
    }

    //cout<< *p << "\n";
    delete [] partBytes;
}

_writeFile 是要写入的文件。

void FileProcessor::writeToFile(const char *buffer,unsigned int size)
{
    if(_writeFile.is_open())
    {
        _writeFile.write(buffer,size);
        _writeFile.flush();
    }
}

在这种情况下,我正在尝试复制一个 zip 文件。 但是在记事本中打开原件和拷贝我注意到虽然它们看起来相同,但在拷贝丢失几个字节的末尾有所不同。

有什么建议吗?

最佳答案

您假设文件大小是 _bufferSize 的倍数。您必须检查 之后 缓冲区中还剩下什么:

while(_file.read(partBytes,_bufferSize)) {
  writeToFile(partBytes,_bufferSize);
}
if(_file.gcount())
    writeToFile(partBytes, _file.gcount());

关于C++ 复制文件。数据不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9343624/

相关文章:

c++ - set 和 compering/sorting functor 或 less 运算符

c# - 是否可以创建可以在 Windows 中以编程方式登录用户的服务或应用程序

c++ - 将持续时间值设为双倍

Java:使用 URL 对象作为 File 对象

c++ - 制作 C++ 应用程序 "Opened with..."

html - css 样式表路径,坚持文件本身所在的位置?

c++ - libjpeg 版本6b jpeg_stdio_src 与 jpeg_mem_src

gcc - 用特定值填充向量 (SSE2) 的最快方法。模板友好

python - 复制 matplotlib 艺术家

linux - 将文件内容复制到其他位置