文件分割与c语言文件结

https://blog.csdn.net/weixin_33754065/article/details/92272447

1、 fread函数原型:

size_t fread ( void *buffer, size_t size, size_t count, FILE *stream) ;

size和count的含义:每次读count个块,每块为size字节

fread的返回值含义为:读到的块数,假定现在返回值为num(size太具有歧义,会让人以为是读到的字节数)

num值的判断:

1.num == count,读操作成功,返回count*size个字节;

2.num == 0,此时fread并不一定是读错了或到文件末尾了,fread函数返回值并没有判断这两种情况,以上两种情况只能用函数ferror和feof判断(返回值非零为正常)

2、分割

#include <iostream>

#include <string>
using namespace std;



#define SPLIT_SIZE (5*1024*1024)

char SpitBuf[SPLIT_SIZE] = { 0 };
int  gBufReadSize = 0;     //当前buf里的实际读入数据

int  gFilesize = 0;   //文件大小
int  gBytesRead = 0;  //已读大小



void  writeFileNum(int i) {
    FILE* wfile = NULL;

    char filename[512];
    sprintf(filename,"file_%d",i);

    wfile = fopen(filename, "wb");
    if (wfile == NULL)
    {
        printf("Open %s error !", filename);
        return;
    }
    int ret = fwrite(SpitBuf, 1, gBufReadSize, wfile);
    printf("ret %d --->!", ret);
    fclose(wfile);
}


void splitFile(char* filePath) {

    FILE* m_file = NULL;
    m_file = fopen(filePath, "rb");
    if (m_file == NULL)
    {
        printf("Open %s error !", filePath);
        return;
    }

    fseek(m_file, 0, SEEK_END);
    gFilesize = ftell(m_file);
    int mytimes = gFilesize / SPLIT_SIZE;
    printf("size %d  splitsize %d  %d --->\n", gFilesize, SPLIT_SIZE, mytimes);
    cout << "times " << mytimes << endl;
    fseek(m_file, 0, SEEK_SET);

    for (int i = 0; i < gFilesize / SPLIT_SIZE + 1; i++) {
        int bytesRead = (int)fread(SpitBuf, 1, SPLIT_SIZE, m_file);
        gBytesRead += bytesRead;
        printf("bytesRead = %d\n", bytesRead);
        gBufReadSize = bytesRead;
        writeFileNum(i);
        cout << i << endl;
     }
  
    fclose(m_file);
    return;
 }

void merge(char* filename,int size) {

    FILE* rfile = NULL;

    FILE* wfile = fopen(filename, "wb");
    if (wfile == NULL)
    {
        printf("Open %s error !", filename);
        return;
    }

    for (int i = 0; i < size; i++) {

        char filename[512];
        sprintf(filename, "file_%d", i);

        FILE* rfile = fopen(filename, "rb");
        if (rfile == NULL)
        {
            printf("Open %s error !", filename);
            return;
        }
        int bytesRead = (int)fread(SpitBuf, 1, SPLIT_SIZE, rfile);
        gBytesRead += bytesRead;
        printf("bytesRead = %d\n", bytesRead);
        gBufReadSize = bytesRead;
        int ret = fwrite(SpitBuf, 1, gBufReadSize, wfile);
        printf("fwiteret %d --->!", ret);
        fclose(rfile);
        
    }
    cout << "before close r" << endl;
  
    cout << "before close w" << endl;
    fclose(wfile);
}

int main()
{
    const char* filePath = "and.pdf";
   // splitFile((char*)filePath);

    merge((char*)"file",3);

  //  std::cout << "Hello World!\n";
}
原文地址:https://www.cnblogs.com/cnchengv/p/15712783.html