c/c++读写文件(c++方法篇)

读写文件操作

c++方法

参考博客:基本函数介绍
直接上代码,如下

void OperationFile_Cplus() {
  ofstream file;
  file.open("D:/test01.txt");
  int nRet = file.is_open();
  if (!nRet) {
    cout << "打开文件失败" << endl;
  }
  long pos1 = file.tellp();
  char ByteToWrite[40] = "\x0a\x0a\x0a\x0a";
  char ByteToRead[40] = { 0 };
  file.write(ByteToWrite,strlen(ByteToWrite));//执行完该函数确实不会立刻写入文件
  file.seekp(0,ios::end);
  long pos2 = file.tellp();
  cout << "文件实际占用的字节数:" << (pos2 - pos1) << endl;
  file.close();

  ifstream file2;
  file2.open("D://test01.txt");
  nRet = file2.is_open();
  if (!nRet) {
    cout << "打开文件失败" << endl;
  }
  pos1 = 0;
  file2.seekg(0, ios::end);
  pos2 = file2.tellg();
  cout << "文件实际占用的字节数:" << (pos2 - pos1) << endl;
  file2.seekg(0, ios::beg);
  file2.read(ByteToRead, pos2 - pos1);
  int num = file2.gcount();
  cout << "实际读到的字节数:" << num <<endl;
  file2.close();

  cout << "================================" << endl;

  file.open("D:/test02.txt",ios::binary);
  nRet = file.is_open();
  if (!nRet) {
    cout << "打开文件失败" << endl;
  }
  pos1 = file.tellp();
  memset(ByteToRead, 0, sizeof(ByteToRead));
  file.write(ByteToWrite, strlen(ByteToWrite));//执行完该函数确实不会立刻写入文件
  file.seekp(0, ios::end);
  pos2 = file.tellp();
  cout << "文件实际占用的字节数:" << (pos2 - pos1) << endl;
  file.close();

  file2.open("D://test02.txt",ios::binary);
  nRet = file2.is_open();
  if (!nRet) {
    cout << "打开文件失败" << endl;
  }
  pos1 = 0;
  file2.seekg(0, ios::end);
  pos2 = file2.tellg();
  cout << "文件实际占用的字节数:" << (pos2 - pos1) << endl;
  file2.seekg(0, ios::beg);
  file2.read(ByteToRead, pos2 - pos1);
  num = file2.gcount();
  cout << "实际读到的字节数:" << num << endl;
  file2.close();
}

这里使用的是ofstreamifstream,当然也可以使用fstream,但是需要注意一下两点:
1.fstream的对象以ios::in|ios::out方式去打开文件时,若文件不存在会打开失败;
2.参考博客【基本函数介绍】中提到可同步的问题,写文件时先写入流缓存,直到触发【同步】过程,在调试过程中针对此问题进行了验证如下图所示,确实存在。【ps:使用c方法也是类似的,调用fwrite函数也不是立即写入文件】
在这里插入图片描述
函数的执行结果和c语言方法相同,如下图所示:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值