码迷,mamicode.com
首页 > 其他好文 > 详细

合并两个文件,替换文件,获取文件大小

时间:2019-05-16 21:44:34      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:否则   lin   获取文件   binary   rem   col   replace   bin   exist   

合并文件   
void OpMergerFile(string readpath, string writepath)
{
//    char cline;
//    ifstream ifile;
//    ofstream ofile;
//    if (_access(readpath.c_str(), 0) == 0) {
//#ifdef WIN32
//        ifile.open(readpath, ios::binary | ios::in);     //读写都要以二进制形式,否则遇到/0就认为结束
//        ofile.open(writepath,  ios::binary | ios::app);
//#else
//        ifile.open(readpath, ios::binary);
//        ofile.open(writepath, fstream::app);
//#endif // WIN32
//        while (ifile.get(cline))
//            ofile << cline;
//
//        ifile.close();
//        ofile.close();
    //}

   char c;
   FILE* rfp, *wfp;
   fopen_s(&rfp, readpath.c_str(), "rb");
  fopen_s(&wfp, writepath.c_str(), "a+b");

  fseek(wfp, 0, SEEK_END); 

  while (fread(&c, 1, 1, rfp))
  fwrite(&c, 1, 1, wfp);
  fclose(rfp); fclose(wfp);

return; }


替换文件

void OpReplaceFile(string readpath,string writepath)
{
    char cline;
    ifstream ifile;
    ofstream ofile;
    if (IfFileExist(readpath.c_str()) && IfFileExist(writepath.c_str())) {
#ifdef WIN32
    ifile.open(readpath, ios::binary);
    ofile.open(writepath, ios::binary);
#else
    ifile.open(readpath);
    ofile.open(writepath);
#endif // WIN32
        
        while(ifile.get(cline))
            ofile << cline;
        ifile.close();
        ofile.close();
    }
    return;
}

拼接文件(保留其中一个文件不变)

void ToRightMergerFile(string MergerFilepath,string HoleFilePath)
{
    std::string tmp = "./intertemp";
    MergerFile(HoleFilePath, tmp);
    MergerFile(MergerFilepath,tmp);
    OpReplaceFile(tmp, MergerFilepath);
    remove(tmp.c_str());
}

 

 获取文件大小

long GetFileLength(const std::string filepath)
{
    long LocalFilelen = 0;
    FILE* pfile;
#ifdef WIN32
    if (fopen_s(&pfile, filepath.c_str(), "r") != 0)
        return 0;
    if(pfile)
    {
        fseek(pfile, 0, SEEK_SET);
        fseek(pfile, 0, SEEK_END);
        LocalFilelen = ftell(pfile);
    }
#else
    pfile = fopen(filepath.c_str(), "r");
    if(pfile)
    {
        fseek(pfile, 0, SEEK_SET);
        fseek(pfile, 0, SEEK_END);
        LocalFilelen = ftell(pfile);
    }
#endif

    fclose(pfile);
    pfile = NULL;
    return LocalFilelen;

 

合并两个文件,替换文件,获取文件大小

标签:否则   lin   获取文件   binary   rem   col   replace   bin   exist   

原文地址:https://www.cnblogs.com/lizhanzhe/p/10878151.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!