读取文件几种方法

来源:互联网 发布:js dom loaded 编辑:程序博客网 时间:2024/06/05 17:31

1.使用Windows API

 HANDLE hFile;

  DWORD nBytes;

  hFile=CreateFile(_T("d://test.txt"),GENERIC_WRITE,FILE_SHARE_WRITE,NULL,CREATE_ALWAYS,0,NULL);

  char msg[]="this is simple example use winows API";

  if(hFile!=INVALID_HANDLE_VALUE)

  {

   WriteFile(hFile,msg,sizeof(msg)-1,&nBytes,NULL);

   CloseHandle(hFile);

  }

  //读取文件

  hFile=CreateFile(_T("d://test.txt"),GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_ALWAYS,0,NULL);

  if(hFile!=INVALID_HANDLE_VALUE)

  {

 char line[256]={0};

 bool bResult;

 bResult=ReadFile(hFile,line,sizeof(line),&nBytes,NULL);

 if(nBytes!=0)

 {

 printf("%s/r/n",line);

 }

 CloseHandle(hFile);

  }

  system("pause");

2.使用STL

写入文件

ofstream out("d://test1.txt");

out<<"this is simple example use stl";

out.close();

//读取文件

ifstream in("d://test1.txt");

char line[256];

in.getline(line,256);

cout<<line<<endl;

system("pause");

3.使用CRT

 

//写入文件

FILE *fp=fopen("d://test2.txt","w");

    fprintf(fp,"CRT读取文件");

fclose(fp);

//读取文件

fp=fopen("d://test2.txt","r");

char line[256];

fscanf(fp,"%s",line);

printf("%s/r/n",line);

fclose(fp);

system("pause");

 

4.是用CRT宽字符

FILE *fp=_wfopen(L"d://test3.txt",L"w,ccs=UNICODE");

fwprintf(fp,L"%s",L"宽字符读取文件");

fclose(fp);

 

fp=_wfopen(L"d://test3.txt",L"r,ccs=UNICODE");

wchar_t line[256];

fwscanf(fp,L"%s",line);

wprintf(L"%s/r/n",line);

fclose(fp);

 

5.使用CRT Safe版本

   FILE *fp;

   fopen_s(&fp,"D://test4.txt","w");

   fprintf_s(fp,"CRT安全版本读取文件","w");

   fclose(fp);

 

   fopen_s(&fp,"d://test4.txt","r");

   char line[256];

   fscanf(fp,"%s",line,256);

   printf_s("%s/r/n",line);

   fclose(fp);

6.使用MFC库

 

  CFile file;

if(file.Open(_T("d://test5.txt"),CFile::modeCreate|CFile::modeWrite))

{

char line[256]="MFC读取文件";

file.Write(line,sizeof(line));

            file.Close();

}

 

if(file.Open(_T("d://test5.txt"),CFile::modeRead))

{

char line[256];

if(file.Read(line,256)!=0)

{

printf("%s/r/n",line);

}

file.Close();

}

 

当然还有CLR的版本,托管的c++不熟悉就不写了......

原创粉丝点击