XY.348 2021-10-27 11:26 采纳率: 100%
浏览 50
已结题

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;
}

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

  • 写回答

2条回答 默认 最新

  • CSDN专家-link 2021-10-27 11:29
    关注
    
    #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;
    }
     
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 11月4日
  • 已采纳回答 10月27日
  • 创建了问题 10月27日