C++ seekg,seekp,tellg,tellp

本文介绍了如何使用C++标准库中的fstream进行文件的读写操作,包括通过seekg和tellg定位输入文件流指针,以及利用seekp和tellp设置输出文件流的指针位置。提供了具体的示例代码说明这些功能的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.      seekg,tellg

Ø  功能:设置输入文件流的文件流指针位置

Ø  示例程序:

例1

// read a file into memory

#include <iostream>     // std::cout

#include <fstream>      // std::ifstream

 

int main () {

 std::ifstream is ("D:/test.txt", std::ifstream::binary);

  if (is) {

    // get length of file:

    is.seekg (0, is.end);//将读取is指针移到离is.end的0处意思是将此指针移到文件末尾

    int length = is.tellg();//返回输入流中的当前字符的位置。   is.seekg (0, is.beg);// 将读取is指针移到离is.beg的0处意思是将此指针移到文件开始

 

 

    // allocate memory:

char * buffer = new char [length+1];

memset(buffer,0,length+1);

 

    // read data as a block:

   is.read (buffer,length);

 

   is.close();

 

    // print content:

   std::cout.write (buffer,length);

 

    delete[] buffer;

  }

 

  return 0;

}

2.      seekp,tellp

Ø  功能:设置输出文件流的文件流指针位置

Ø  示例程序

例1

#include <fstream>      // std::ofstream
 
int main () {
 
  std::ofstream outfile;
  outfile.open ("D:/test.txt");
 
  outfile.write ("This is an apple",16);
  long pos = outfile.tellp();//返回当前文件指针的位置
  outfile.seekp (pos-7);
  outfile.write (" sam",4);
 
  outfile.close();
 
  return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值