MFC结构体数据文件读写实例
程序功能将结构体内数组数据写入文件和读出
2Dlg.h中代码:
typedef struct Student {
int nNum[1000];
float fScore;
CString sss;
}stu;
class CMy2Dlg : public CDialog
{
// Construction
public:
CMy2Dlg(CWnd* pParent = NULL); // standard constructor
stu stu1;
...
}
2Dlg.cpp中代码:
BOOL CMy2Dlg::OnInitDialog()
{
CDialog::OnInitDialog();
for(int i=0; i<=5 ; i++)
{
stu1.nNum[i] =i;
}
...
}
void CMy2Dlg::OnButton1()
{
CString strFileName,m_strCurDataPath;
strFileName.Format("%s%s.MBD",m_strCurDataPath,
CTime::GetCurrentTime().Format("%Y%m%d%H%M%S"));
CFile file;
file.Open(strFileName,CFile::modeCreate|CFile::modeWrite);
file.Write(&stu1, sizeof(stu1));
}
void CMy2Dlg::OnButton2()
{
CString strFileName;
CFileDialog dlg(TRUE,"",strFileName,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
"数据文件(*.MBD)|*.MBD||");
if(dlg.DoModal() == IDOK)
{
strFileName = dlg.GetPathName();
CFile file;
file.Open(strFileName,CFile::modeRead);
file.Read(&stu1, sizeof(stu1));
for(int i=1;i<=5;i++)
{
CString str1;
str1.Format("%d",stu1.nNum[i]);
SetDlgItemText(IDC_STATIC1,str1);
Sleep(1000);
}
}
}
运行程序