c++\把读取函数的代码封装成函数并调用,还有怎么输出读取函数的数据


#include <fstream> // ifstream, ifstream::in
#include <iostream>
using namespace std;

int main()
{
    // 1. 打开图片文件
    ifstream is("test.jpg", ifstream::in | ios::binary);
    // 2. 计算图片长度
    is.seekg(0, is.end);  //将文件流指针定位到流的末尾
    int length = is.tellg();
    is.seekg(0, is.beg);  //将文件流指针重新定位到流的开始
    // 3. 创建内存缓存区
    char* buffer = new char[length];
    // 4. 读取图片
    is.read(buffer, length);
    cout << length << endl;
    // 到此,图片已经成功的被读取到内存(buffer)中
    delete[] buffer;
    return 0;
}

请问怎么把上面读取图片的代码封装成函数并调用,还有怎么输出读取的数据呢?


#include <fstream> // ifstream, ifstream::in
#include <iostream>
using namespace std;

char * readFile(int &length)
{
    // 1. 打开图片文件
    ifstream is("test.jpg", ifstream::in | ios::binary);
    // 2. 计算图片长度
    is.seekg(0, is.end);  //将文件流指针定位到流的末尾
    length = is.tellg();
    is.seekg(0, is.beg);  //将文件流指针重新定位到流的开始
    // 3. 创建内存缓存区
    char* buffer = new char[length];
    // 4. 读取图片
    is.read(buffer, length);
    return buffer;
}

int main()
{
    int length;
    char *buffer = readFile(length);
    cout << length << endl;
    // 到此,图片已经成功的被读取到内存(buffer)中
    if(buffer != NULL)
        delete[] buffer;
    return 0;
}
 

把char *buffer当做返回值,或者作为返回参数