bin文档读写

今天遇到问题。之前测试模组的时候,保存的测试数据bin文档多了2个byte数据。
解决紧急问题当然使用最熟悉方式。
于是用我准备的TestWinControl工程写了如下代码。

bin Files文件夹中有100个1~100编号的.bin文档。重新读写后
bin文件夹中生成100个已经去掉最后两个byte的.bin文档。

#include "stdafx.h"
#include <afx.h>
#include <iostream>

using namespace std;

CString GetExeDir()
{
    CString ExePath, ExeDir;
    TCHAR tempPath[MAX_PATH] = {0};
    GetModuleFileName(NULL,tempPath,MAX_PATH);
    ExePath = tempPath;
    //NOTICE: 得到的路径最后带 *\*
    ExeDir  = ExePath.Left( ExePath.ReverseFind(_T('\\'))+1) ;
    return ExeDir;
}

void WriteBin(CString szPath, unsigned char* data, int size)
{
    FILE* pFile;
    if (_wfopen_s(&pFile, szPath.GetBuffer() , _T("wb+")) == 0)
    {
        fwrite(data, 1, size, pFile);
        fclose(pFile);
        szPath.Format(_T("%s write"),szPath);
        cout << "write size: " << size << endl;
    }
}

void ReadBin(CString szPath, unsigned char* data, int size)
{
    FILE* pFile;
    if (_wfopen_s(&pFile, szPath.GetBuffer() , _T("rb+")) == 0)
    {
        fread(data, 1, size, pFile);
        fclose(pFile);
        szPath.Format(_T("%s read"),szPath);
        cout << "read size: " << size << endl;
    }
}

int main()
{
    const int size = 1406;
    unsigned char data[size] = {0};
    memset(data, 0, size);

    const int wsize = 1404;
    unsigned char wdata[wsize] = {0};
    memset(wdata, 0, wsize);

    CString exeDir = GetExeDir();
    CString readPath;
    CString writePath;
    CreateDirectory(exeDir + _T("bin\\"), NULL);

    CFileFind finder;
    BOOL bw = finder.FindFile(exeDir + _T("bin Files\\*.bin"));
    while(bw)
    {
        bw = finder.FindNextFile();
        if (finder.IsDots()) continue;
        if (finder.IsDirectory()) continue;

        CString fileName = finder.GetFileName();
        readPath = exeDir + _T("bin Files\\") + fileName;
        writePath = exeDir + _T("bin\\") + fileName;
        ReadBin(readPath, data, size);
        memcpy(wdata, data, wsize);
        WriteBin(writePath, wdata, wsize);
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

devilthelover

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值