bin文档读写

来源:互联网 发布:linux查看程序进程号 编辑:程序博客网 时间:2024/06/10 23:50

今天遇到问题。之前测试模组的时候,保存的测试数据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