滴水-文件读写 开源代码

#include <stdio.h>
#include <malloc.h>
#include <string.h>
//此处是禁用函数警报
#define _CRT_SECURE_NO_DEPRECATE
#pragma warning(disable:4996)
FILE* openFile(char* filePath, char* type);//打开文件函数 返回指向文件缓冲区流头指针

int getSize(FILE* fileAdress);//得到文件大小函数 返回文件大小

char* allotspace(int size);//分配内存空间函数 根据得到的文件大小 返回内存空间首地址

char* readFiletoMemory(FILE* fileHeadAdress, char* head, int size);//将文件写入分配好的空间的函数 返回已经写入数据的内存空间首地址

int writeMemorytoFile(char* filePath, char* type, char* head, int size);//将内存中的数据写出到文件函数

int main()
{
    //给定读取的文件路径
    char filePath[] = "D:\\测试程序.exe";
    //给定读写类型
    char type[] = "rb+";
    //打开文件传递文件流首地址
    FILE* fileAdress = openFile(filePath, type);
    //通过文件流首地址得到文件大小
    int fileSize = getSize(fileAdress);
    //通过文件大小开辟内存空间并初始化
    char* head = allotspace(fileSize);
    //将文件流中数据读入开辟的内存空间内
    head = readFiletoMemory(fileAdress, head, fileSize);
    //给定写出的文件路径
    char filePath2[] = "D:\\10.exe";
    //给定读写类型
    char type2[] = "wb+";
    //将内存空间内的数据写出
    writeMemorytoFile(filePath2, type2, head, fileSize);
    //关闭文件流
    fclose(fileAdress);
    //释放内存
    free(head);

    return 0;
}




//打开文件函数 返回指向文件缓冲区流头指针
FILE* openFile(char* filePath, char* type) {
    FILE* fileAdress;
    //通过传入的文件地址以及读写类型打开文件创建文件流
    if (!(fileAdress = fopen(filePath, type)))
    {
        printf("获取文件出错!\n");
        return 0;
    }
    return fileAdress;
}

//得到文件大小函数 返回文件大小
int getSize(FILE* fileAdress) {
    int size;
    //定位文件末尾
    fseek(fileAdress, NULL, SEEK_END);
    //得到文件流大小
    size = ftell(fileAdress);
    //重定位文件开头
    fseek(fileAdress, NULL, SEEK_SET);
    return    size;
}

//分配内存空间函数 根据得到的文件大小 返回内存空间首地址
char* allotspace(int size) {
    char* head;
    //根据文件大小分配内存空间
    if (!(head = (char*)malloc(size))) {
        printf("分配空间失败!\n");
        return 0;
    }
    //使用1初始化size大小已经分配的内存空间
    memset(head, 1, size);
    //返回分配初始化完毕的内存空间首地址
    return head;
}

//将文件写入分配好的空间的函数 返回已经写入数据的内存空间首地址
char* readFiletoMemory(FILE* fileHeadAdress, char* head, int size) {
    //通过传入的文件地址以及开辟的内存空间首地址和文件大小将文件数据写入分配好的内存空间中
    if (!(fread(head, 1, size, fileHeadAdress) == size)) {
        printf("文件数据写入内存出错!");
        return 0;
    }
    //读取文件数据写入内存
    return head;
}

//将内存中的数据写出到文件函数
int writeMemorytoFile(char* filePath, char* type, char* head, int size) {
    //定义创建文件流
    FILE* fileAdress = openFile(filePath, type);
    //读取内存数据写出到文件
    if (!(fwrite(head, 1, size, fileAdress) == size)) {
        printf("内存数据写出到文件出错!\n");
        return 0;
    }
    return 1;
}

代码来源 https://zhuanlan.zhihu.com/p/106775151

我是懒得写了,讲解视频

https://www.bilibili.com/video/BV1wG411773m/

posted @ 2022-10-12 19:45  逆向狗  阅读(32)  评论(0)    收藏  举报