zoukankan      html  css  js  c++  java
  • 20091113 08:37 实现文件读写操作的几种方法

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

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

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

  • 相关阅读:
    一段asp程序中效率极低的代码,造成连接数据库超时
    古月照今尘
    with C# Code run on Dynamicx AX 2009
    Using X++ Code export to methods list of Class
    Useing X++ code saved as full Screen Resolution Image
    Find out field list(EDT) on a AX Table
    进制转换
    with tableId and fieldname get to the field value on a Common table records
    Set focus on the dialog field
    Label in Dynamics AX 2009
  • 原文地址:https://www.cnblogs.com/lidabo/p/3043819.html
Copyright © 2011-2022 走看看