最近帮导师做一个项目,遇到了需要对TXT文档中的数据进行高低字节转换的问题,这里首先放一下我们需要实现的效果,需要程序示例的请下载:高低字节转换Demo

原理其实非常简单,主要是如下几个步骤:

Step1:导入文件,并将文件内容放入CString中存储

Step2:去除文件中字节间的空格,形成一个连续的字符串

Step3:对奇数(高|低)和偶数(低|高)位进行对调

Step4:对对调后的字符串进行拼接并加上空格以方便查看

Step5:对前后字符串长度进行比对校验

Step6:将新行程的字符串写入文本

具体的核心代码如下:

获取写文件路径:

void CMFCApplication6Dlg::OnBnClickedButton2()
{
	// TODO:  在此添加控件通知处理程序代码
	setlocale(LC_CTYPE, "chs");

	CFileDialog dlgFile(FALSE, _T("*.txt"), NULL, OFN_HIDEREADONLY, _T("Describe File(*.txt)|*.txt|All Files(*.*)|*.*||"), NULL);
	if (IDOK == dlgFile.DoModal())
	{
		FileName = dlgFile.GetPathName();
	}
	else
	{
		return;
	}
	SetDlgItemText(IDC_EDIT6, FileName);
}

读文件以及数据处理:

void CMFCApplication6Dlg::OnBnClickedButton1()
{
	CString strPath, strText = _T("");
	CFileDialog dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
		_T("txt记事本(*.txt)|*.txt|ini文档(*.ini)|*.ini|pem文档(*.pem)|*.pem||"), AfxGetMainWnd());

	if (IDOK == dlg.DoModal())
	{
		strPath = dlg.GetPathName();
		//显示文件的路径
		SetDlgItemText(IDC_EDIT2, strPath);

		//获取文件长度
		string sPath = strPath.GetBuffer(strPath.GetLength() + 1);

		FILE* pFile = nullptr;        //pFile = fopen(sPath.c_str(), "r+t");
		fopen_s(&pFile, sPath.c_str(), "r");

		if (pFile)
		{
			fseek(pFile, 0, SEEK_END);
			int nFileLen = ftell(pFile);
			char* buf = new char[nFileLen+1];

			fseek(pFile, 0, SEEK_SET);
			fread(buf, sizeof(char), nFileLen, pFile);
			fclose(pFile);
			buf[nFileLen] = 0;;
			strText.Format(_T("%s"), buf);
			SetDlgItemText(IDC_EDIT4, strText);
			int length = strText.GetLength();
			CString length_show;
			length_show.Format("%d", length);
			SetDlgItemText(IDC_EDIT3, length_show);

			delete[] buf;
			//删除掉文件中的换行符和空格
			strText.Replace("\r\n", "");
			//删除掉文件中的空格
			strText.Replace(" ", "");
			
			
			CString show;
			CString result;
		   //字符串的截取和插值
			for (int i= 0; i < length/3; i=i+2)
			{
				CString temp;
				CString temp1;
				//字符串截取
				temp = strText.Mid(i*2,2);
				temp1 = strText.Mid(i*2+2, 2);
				show = temp1 +" "+ temp;
				result += show+" ";
			}
			
			//显示处理后的字符串
			result = result.Left((result.GetLength()-1));
			SetDlgItemText(IDC_EDIT1, result);

			int length1 = result.GetLength();
			CString length_show1;
			length_show1.Format("%d", length1);
			SetDlgItemText(IDC_EDIT7, length_show1);
			int len = 0;
			CString path = "";

			CFile file(FileName, CFile::modeReadWrite | CFile::modeCreate);
			file.Write(result, result.GetLength());
			len = file.GetLength();
			//file.Flush();
			file.Close();
			if (length==length1)
			{
				MessageBox("转换成功,数据校验正确","提示");
			}
			else
			{
				MessageBox("转换成功,数据校验异常,请检查源文件内容!","警告!");
			}

		}
	}
}

其实原理非常简单,纯使用CString的函数来操作,大功告成啦