文件读写

fstream 二进制文件读写

// Copy a file
#include <fstream>      // std::ifstream, std::ofstream

int main () {
  std::ifstream infile ("test.txt",std::ifstream::binary);
  std::ofstream outfile ("new.txt",std::ofstream::binary);

  // get size of file
  infile.seekg (0,infile.end);
  long size = infile.tellg();
  infile.seekg (0);

  // allocate memory for file content
  char* buffer = new char[size];

  // read content of infile
  infile.read (buffer,size);

  // write to outfile
  outfile.write (buffer,size);

  // release dynamically-allocated memory
  delete[] buffer;

  outfile.close();
  infile.close();
  return 0;
}

文本文件追加写入

record.hpp

class Record
{
public:
    Record();
    ~Record();
    bool OpenFile(std::string path);
    bool Append(std::string str);
    bool Close();
    bool isOpen(){return opensts;};
private:
    std::fstream fs;
    bool opensts = false;   
   
};

record.cpp

bool Record::OpenFile(std::string path)
{
    fs.open(path, std::fstream::in | std::fstream::app);
    opensts = fs.is_open();
    return opensts;
}

bool Record::Append(std::string str)
{
    if (opensts)
    {
        fs << str;
        fs.flush();
        return true;
    }
    return false;
}

bool Record::Close()
{
    if (opensts)
    {
        fs.close();
        return true;
    }
    return false;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。