C C++ 和 windows 实现文件的读写操作,

#include
#include
#include
#include
using namespace std;

// c++ API    path " read.txt",  name  "write.txt"
void  readand_write(char* path,char* name)
{
    char* filedata = NULL;
    std::ifstream file_;
    std::ofstream outfile;

    file_.open(path, std::ios::binary);
    //获取文件长度
    streampos pos = file_.tellg();
    file_.seekg(0,ios::end);
    int size = file_.tellg();
    file_.seekg(pos);
    ////
    filedata = new char [size + 1];
    file_.read(filedata,size);
    filedata[size] = 0;
    outfile.open(name);
    outfile<

    delete [] filedata;
    outfile.close();
    outfile.clear();
    file_.close();
    file_.clear();
}
// windows API
void ReadF(wchar_t* str,char* buffer)
{
        HANDLE pfile;
        pfile = ::CreateFile(str,GENERIC_READ ,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); 
        if ( pfile == INVALID_HANDLE_VALUE)
        {
                cout<<"打开文件失败" <                 CloseHandle(pfile); // 一定注意在函数退出之前对句柄进行释放
                return;
        }
        DWORD filesize = GetFileSize(pfile,NULL);
        DWORD readsize;
        ReadFile(pfile,buffer,filesize,&readsize,NULL);
        buffer[filesize] = 0;
        CloseHandle(pfile); // 关闭句柄
}
void WriteF(wchar_t* str,const char* buffer,int size)
{
        HANDLE pfile;
        pfile = ::CreateFile(str,GENERIC_WRITE,0,NULL,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,NULL); 
        if ( pfile == INVALID_HANDLE_VALUE)
        {
                cout<<"打开文件失败" <                 CloseHandle(pfile); // 一定注意在函数退出之前对句柄进行释放
                return ;
        }
        DWORD readsize;
        WriteFile(pfile,buffer,size,&readsize,NULL);
        CloseHandle(pfile); // 关闭句柄
}
//c语言 API
void read_w(char* path,char* name)
{
     FILE *fp;
    char ch ;
    char str[1000] = {0};
    fp = fopen(path,"r");
    if(fp == NULL)
        printf("file cannot open \n");
    int i = 0;
      while((ch = fgetc(fp)) != EOF)
      {
              str[i] = ch;
              i++;
          //printf("%c",ch);
      }
      printf("%s",str);

//fp = fopen(path,"w");

    //char p_ch = 'k';
 //       fputc(p_ch,fp);

   fclose(fp);
}

/////////////////////

总结:

由于基础还不是很稳,今天详细梳理了一下关于C语言接口,C++接口,Windows接口实现文件的操作问题。

C语言对文件操作更细致,更容易精确到单个字符;C++更灵活一些,有较多的实现方式,如:流重定向等;Windows接口就更简单了,只要掌握住CreateFile(),ReadFile(),WriteFile(),参数即可,个人认为容易实现,没有那么多细节。

 

 

你可能感兴趣的:(C++)