C++文件读写

对输入流操作:seekg()与tellg()
对输出流操作:seekp()与tellp()
下面以输入流函数为例介绍用法:
seekg()是对输入文件定位,它有两个参数:第一个参数是偏移量,第二个参数是基地址。
对于第一个参数,可以是正负数值,正的表示向后偏移,负的表示向前偏移。而第二个参数可以是:
ios::beg:表示输入流的开始位置
ios::cur:表示输入流的当前位置
ios::end:表示输入流的结束位置
tellg()函数不需要带参数,它返回当前定位指针的位置,也代表着输入流的大小。

#include <iostream>
#include <fstream>//读写操作,对打开的文件可进行读写操作
#include <string>//c++风格字符串
#include <cstring>//c风格字符串
//#include <ifstream>文件读操作,存储设备读区到内存中
//#include <ofstream>文件写操作 内存写入存储设备
using namespace std;


int main()
{
    //============================================//
    cout << "Hello world!" << endl;


    //文件内存写到磁盘
    ofstream fout("001.txt");//打开待写文件


    string a="where is my future !";//cha* a="where is my future !";


    if (fout.is_open())
        fout<<"hello cpp.\n"<<a<<endl;//写到文件
    else
        cout<<"file open failed"<<endl;
    fout.close();


    //文件磁盘读到内存
    char buffer[256];


    ifstream fin("002.txt");//打开待写文件
    if (! fin.is_open())
       { cout << "Error opening file"; throw 1; }
       while (!fin.eof() )
       {
           fin.getline (buffer,100);//按行读入到buffer
           cout <<"read message: "<< buffer << endl;
       }
       fin.close();


       char *b = "nihao";
       cout<<b<<"字符串的长度="<<strlen(b)<<endl;


    //=========================================//
    //=========================================//
    //read 003.txt




    //const char * filename2 = "D:\\CPP\\readwrite\\003.txt";


    ifstream in ("D:\\CPP\\readwrite\\003.txt", ios::in|ios::binary|ios::ate);
    if (! in.is_open())
       { cout << "Error opening file 003.txt"; throw 1; }


    // get length of file:
    in.seekg (0, in.end);//Set position in input sequence end
    long length = in.tellg();
    in.seekg (0, in.beg);//Set position in input sequence begin


    // allocate memory:
    char* buffer2 = new char [length];//buffer2 必须是char*


    // read data as a block:
    in.read (buffer2, length);
    in.close();


    //print content:
    cout<<"size="<<length<<endl;
    cout <<buffer2<<endl;


    //-----write to 004.txt--------//


    //const char * filename3 = "004.txt";//文件名 char*
    ofstream out ("004.txt", ios::out|ios::binary|ios::ate);
    if (!out.is_open())
       { cout << "Error opening file 004.txt"; throw 0; }


    // write to out
    out.write(buffer2, length);//buffer2 必须是char *
    out.close();


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


    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值