实现文件读写操作的几种方法
下面为实现文件读取数据的代码:
//以下为用C语言读取文件
FILE *pfile=fopen("2.txt","r");
char *pbuf;
fseek(pfile,0,SEEK_END);
long len=ftell(pfile);
pbuf=new char[len+1];
pbuf[len]=0;
rewind(pfile);
fread(pbuf,1,len,pfile);
MessageBox(pbuf);
fclose(pfile);
//以下为用C++语言读取文件
char ch[100];
memset(ch,0,100);
ifstream ifs("3.txt");
ifs.read(ch,100);
MessageBox(ch);
ifs.close();
//以下为用WIN32 API读取文件
HANDLE hfile;
hfile=CreateFile("4.txt",GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
char ch[100];
DWORD reads;
ReadFile(hfile,ch,100,&reads,NULL);
ch[reads]=0;
MessageBox(ch);
CloseHandle(hfile);
//以下为用MFC读取文件
CFile file("5.txt",CFile::modeRead);
char *pbuf;
DWORD len;
len=file.GetLength();
pbuf=new char[len+1];
pbuf[len]=0;
file.Read(pbuf,len);
MessageBox(pbuf);
file.Close();
下面为实现文件写入数据的代码:
FILE *pfile=fopen("1.txt","w");
fwrite("Hello,every one!",1,strlen("Hello,every one!"),pfile);
fflush(pfile);
fclose(pfile);
//以下为用C++语言写入文件
ofstream ofs("3.txt");
ofs.write("Please help me!",strlen("Please help me!"));
ofs.close();*/
//以下为用WIN32 API写入文件
HANDLE hfile;
hfile=CreateFile("4.txt",GENERIC_WRITE,0,NULL,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,NULL);
DWORD written;
WriteFile(hfile,"welcome!",strlen("welcome!"),&written,NULL);
CloseHandle(hfile);
//以下为用MFC写入文件
CFile file("5.txt",CFile::modeCreate|CFile::modeWrite);
file.Write("Tomorrow is anthor day!",strlen("Tomorrow is anthor day!"));
file.Close();