6/24/10

Read And write data using file(MFC)

Buzz It
#include_afxwin.h_ //replace "_"with"<>"
#include_afxext.h_
#include "resource.h"

class myframe:public CFrameWnd
{
private:CStdioFile fp;

public:
myframe()
{
Create (0,"Writing and reading data",WS_OVERLAPPEDWINDOW,rectDefault,0,MAKEINTRESOURCE(IDR_MENU1));
fp.Open("test.txt",CFile::modeCreateCFile::modeReadWrite);
}
void writedata()
{

char str[40];
int i;
struct record
{
char name[20];
int age;float salary;
};

record e[]={
{"AAA",11,1111.11f},
{"BBB",22,2222.22f},
{"CCC",33,3333.33f},
{"DDD",44,4444.44f}
};
fp.SeekToBegin();
for(i=0;i<=3;i++)
{
sprintf(str,"%s%d%.2f\n",e[i].name,e[i].age,e[i].salary);
fp.WriteString(str);
}
}
void readdata()
{
CString str;
char nm[20],temp[20];
int ag;
float sr;

if(fp.GetLength()==0)
{
MessageBox("File is empty","Read record");
return;
}

fp.SeekToBegin();
while(fp.ReadString(str)!=NULL)
{
sscanf (str,"%s%d%f",nm,&ag,&sr);
str ="Name:";
str+=nm;

str+="\nAge:";
sprintf(temp,"%d",ag);
str+=temp;

str+="\nSalary:";
sprintf(temp,"%2f",sr);
str+=temp;
MessageBox(str,"record.....");
}
}
void OnDestroy()
{
fp.Close();
CFrameWnd::OnDestroy ();
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_COMMAND(101,writedata)
ON_COMMAND(201,readdata)
ON_WM_DESTROY()
END_MESSAGE_MAP()
class myapp:public CWinApp
{
public:
int InitInstance()
{
myframe *p;p=new myframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
myapp a;


OUTPUT

0 comments:

Post a Comment