DoubleLi

qq: 517712484 wx: ldbgliet

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  4737 随笔 :: 2 文章 :: 542 评论 :: 1615万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

实现文件读写操作的几种方法

下面为实现文件读取数据的代码:

//以下为用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();

posted on   DoubleLi  阅读(327)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示