文件IO操作之文件指针

4、小作业:
通过文件读写的方式,自己实现一个函数,实现文件的拷贝功能。

#include <iostream>
#include <fstream>
using namespace std;
bool copy_file(const char* x, const char* y )
{
    //读取
    ifstream read_file;
    read_file.open(x,ios::binary);
    if (!(read_file.is_open()))
    {
        cout << "错误" << endl;
        return 0;
    }
    read_file.seekg(0,ios::end);
    int file_len = read_file.tellg();
    read_file.seekg(0,ios::beg);
    char* buffer = new char[file_len];
    memset(buffer, 0, file_len);
    read_file.read(buffer, file_len);
    if (!read_file.good())
    {
        cout << "错误" << endl;
        return 0;
    }
    read_file.close();
    //写入
    ofstream write_file;
    write_file.open(y,ios::binary);
    if (!(write_file.is_open()))
    {
        cout << "错误" << endl;
        return 0;
    }
    write_file.write(buffer, file_len);
    write_file.close();
    delete[] buffer;
    return 1;
}
int main()
{
    char* in_file = "d://VC API与MFC参考例程.CHM";
    char out_file[] = "c://参考例程.CHM";
    bool is_copy_ok = 0;
    is_copy_ok = copy_file(in_file, out_file);
    cout << is_copy_ok << endl;
    return 0;
}

 

posted on 2021-01-14 19:14  SakuraQAQ  阅读(120)  评论(0)    收藏  举报

导航