使用MFC生成随机数
创建界面
两个编辑框,一个用于保存生成的随机数文件,另一个用于定义生成数据量的大小,这里生成的数据是十六进制保存的。
生成数据并保存
在xxxdlg.cpp中需要include time.h
void RdmToolsDlg::OnBnClickedButtonRandom()
{
UINT m_u32Size;
CString m_csSize;
UpdateData(true);
GetDlgItem(IDC_EDIT_SIZE)->GetWindowText(m_csSize);
if (m_csSize == _T("0") || m_csSize.IsEmpty())
{
AfxMessageBox("Please enter a right number!");
}
m_u32Size = _ttoi(m_csSize);
CString filepath;
GetDlgItem(IDC_EDIT_PATH)->GetWindowText(filepath);
CFile File;
CFileException e;
if (!File.Open(filepath, CFile::modeCreate | CFile::modeReadWrite, &e))
{
CString strErr;
strErr.Format(_T("File could not be opened %d\n"), e.m_cause);
MessageBox(strErr);
}
CString strres, strtmp;
srand((unsigned)time(NULL));
for (int i = 0; i < m_u32Size; i++)
{
strtmp.Format(_T("%.2x"), rand() % 256);
strres += strtmp;
if ((i+1) % 4 == 0)
{
strres += "\r\n";
}
}
File.Write(strres, strlen(strres));
File.Close();
AfxMessageBox("File generated.");
}
测试的时候发现了一个问题,每次生成的数都是一样的,问题出在==strtmp.Format(_T(“%.2x”), rand() % 256);==这里,这里不能使用_T(),否则每次保存下来的值都会是一样的,直接去掉就可以。
strtmp.Format("%.1x", rand() % 16);
修正后代码
void RdmToolsDlg::OnBnClickedButtonRandom()
{
UINT m_u32Size;
CString m_csSize;
UpdateData(true);
GetDlgItem(IDC_EDIT_SIZE)->GetWindowText(m_csSize);
if (m_csSize == _T("0") || m_csSize.IsEmpty())
{
AfxMessageBox("Please enter a right number!");
}
m_u32Size = _ttoi(m_csSize);
CString filepath;
GetDlgItem(IDC_EDIT_PATH)->GetWindowText(filepath);
CFile File;
CFileException e;
if (!File.Open(filepath, CFile::modeCreate | CFile::modeReadWrite, &e))
{
CString strErr;
strErr.Format(_T("File could not be opened %d\n"), e.m_cause);
MessageBox(strErr);
}
CString strres, strtmp;
srand((unsigned)time(NULL));
for (int i = 0; i < m_u32Size; i++)
{
strtmp.Format("%.2x", rand() % 256);
strres += strtmp;
if ((i+1) % 4 == 0)
{
strres += "\r\n";
}
}
File.Write(strres, strlen(strres));
File.Close();
AfxMessageBox("File generated.");
}
|