1. 程式人生 > >c++用檔案流實現檔案拷貝

c++用檔案流實現檔案拷貝

之前用c++作後臺的時候碰到一個問題:返回一張圖片資料。查了一些資料終於解決了。核心就是檔案流怎麼讀寫的問題,已經將問題簡化為檔案拷貝,程式碼如下:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    cout << "Content-Type:image/png\r\n\r\n";
    fstream file;
    file.open("1.png", ios::binary|ios::in|ios::ate);   //開啟時指標在檔案尾
    int length = file.tellg();
    char* imgData = new char[length];
    file.seekg(0);
    file.read(imgData, length);  //二進位制只能用這個讀
    
    fstream file2;
    file2.open("2.png", ios::binary|ios::out);
    file2.write(imgData, length);   //二進位制只能用這個寫
    cout << "ok";
    
    return 0;
}

結果:
在這裡插入圖片描述
原來是不存在2.png的