win32和mfc读写文件

来源:互联网 发布:linux升级ruby版本 编辑:程序博客网 时间:2024/05/16 01:54

wn32

#include <iostream>#include <windows.h>int main (void){//写文件HANDLE hFile=CreateFile(TEXT("1.txt"),GENERIC_WRITE,NULL,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);if (hFile){DWORD dwWrites=0;if (WriteFile(hFile,TEXT("我是你的大皇冠"),ARRAYSIZE(TEXT("我是你的大皇冠")),&dwWrites,NULL)){CloseHandle(hFile);}}//读文件hFile=CreateFile(TEXT("1.txt"),GENERIC_READ,NULL,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);if (hFile){TCHAR szText[100]={0};DWORD dwRead=0;if (ReadFile(hFile,szText,100,&dwRead,NULL)){CloseHandle(hFile);std::cout<<szText<<std::endl;}}return 0;}/*2015年4月1日22:38:00程序执行结果如下:我是你的大皇冠请按任意键继续. . .*/

 

 

mfc


 

#include <stdio.h>#include <afxwin.h>#include <windows.h>#include <iostream>int main (void){CFile file(TEXT("1.txt"),CFile::modeCreate | CFile::modeWrite);file.Write(TEXT("我是你的大皇冠"),ARRAYSIZE(TEXT("我是你的大皇冠")));file.Close();CFile fileRead(TEXT("1.txt"),CFile::modeRead);DWORD nlen=fileRead.GetLength();char *pBuff=new char[nlen+1];fileRead.Read(pBuff,nlen);std::cout<<pBuff<<std::endl;delete []pBuff;return 0;}/*2015年4月1日22:47:40程序执行结果如下:我是你的大皇冠请按任意键继续. . .*/


 

 

mfc

#include <afxwin.h>         // MFC 核心组件和标准组件#include <afxext.h>         // MFC 扩展#include <afxdisp.h>        // MFC 自动化类#include <stdio.h>#include <afxwin.h>#include <windows.h>#include <iostream>int main (void){CFileDialog fileDlg(FALSE);fileDlg.m_ofn.lpstrFilter=TEXT("Text Files(*.txt)\0*.txt\0All Files(*.*)\0*.*\0\0");fileDlg.m_ofn.lpstrDefExt=TEXT("txt");if (IDOK==fileDlg.DoModal()){CFile file(fileDlg.GetPathName(),CFile::modeCreate|CFile::modeWrite);file.Write(TEXT("我是你的大皇冠"),ARRAYSIZE(TEXT("我是你的大皇冠"))+1);file.Close();}CFileDialog fileDlgRead(TRUE);fileDlgRead.m_ofn.lpstrFilter=TEXT("Text Files(*.txt)\0*.txt\0All Files(*.*)\0*.*\0\0");fileDlgRead.m_ofn.lpstrDefExt=TEXT("txt");if (IDOK==fileDlgRead.DoModal()){CFile file(fileDlgRead.GetPathName(),CFile::modeRead);DWORD nlen=file.GetLength();char *pbuff=new char[nlen+1];file.Read(pbuff,nlen);std::cout<<pbuff<<std::endl;file.Close();}return 0;}/*2015年4月1日23:06:57程序执行结果如下:我是你的大皇冠请按任意键继续. . .*/


 

TCHAR szTime[64]={0};TCHAR szText[256]={0};CFile fLog;fLog.Open(TEXT("1.txt"), CFile::modeCreate|CFile::modeNoTruncate|CFile::modeReadWrite );CTime time = CTime::GetCurrentTime() ;_sntprintf(szTime,sizeof(szTime),TEXT( "%d-%d-%d %d:%d:%d" ) ,time.GetYear() ,time.GetMonth() ,time.GetDay() ,time.GetHour() ,time.GetMinute() ,time.GetSecond());fLog.SeekToEnd(); int strLength=lstrlen(szText);#ifdef _UNICODEBYTE bom[2] = {0xff, 0xfe};fLog.Write(bom,sizeof(BYTE)*2);strLength*=2;#endiffLog.Write(szText,strLength);fLog.Close();


0 0
原创粉丝点击