c++读写文件

在代码里面有一个地方没有涉及到缓冲
强制缓冲可以通过flush 和endl,close,或者是明确调用函数sync()去刷新

//
//  main.cpp
//  use_fstream
//
//  Created by bikang on 16/10/10.
//  Copyright (c) 2016年 bikang. All rights reserved.
//

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

//字符串转换
void charChage();

//字符文件读写
void treadWriteCharacter();
//二进制文件读写
void tReadWriteBinary();





int main(int argc, const char * argv[]) {
    tReadWriteBinary();
    //treadWriteCharacter();
    //tstream();
    //charChage();
    return 0;
}
//读写文件
void treadWriteCharacter(){
    //读文件
    char buf[256];
    //ifstream fpin;
    fstream fpin;
    string s1 = "";
    fpin.open("t.log",ios::in);

    //fstream fpout
    ofstream fpout;
    fpout.open("t2.log",ios::out);

    if(fpin && fpout){
        while(!fpin.eof()){
            fpin.seekg(1, ios::cur);
            fpin.getline(buf, 200);
            s1.append(buf);
            s1.append("\n");
            cout << fpin.tellg()<<endl;
            cout << buf<<endl;
            fpout << buf<<endl;
            cout << fpout.tellp() << endl;
            fpout.seekp(1,ios::cur);
        }
        fpin.close();
        fpout.close();
    }
    cout << "###############\n";
    //cout <<s1 <<endl;
}
//二进制读写文件
void tReadWriteBinary(){
    cout << "t"<<endl;
    ifstream fpin;
    fpin.open("t.log",ios::in | ios::binary);

    char buf[256];

    ofstream fpout;
    fpout.open("t3.log",ios::out | ios::binary);

    if(fpin && fpout){
        while(!fpin.eof()){
            fpin.read(buf, 200);
            cout << buf;
            fpout.write(buf, 200);
        }
        fpout.close();
        fpin.close();
    }
    return;
}

void charChage(){
    //1. string转const char*
    string s ="hello cpp";
    const char* c_s = s.c_str();

    cout << c_s << endl;

    //2. const char*转string 直接赋值即可
    // char* 转string也可以这么干
    const char* c_s2 ="hello cpp";
    string s2(c_s2);
    cout << s2<<endl;

    //3. string转char*
    string s3 ="hello cpp";
    char* c;
    const size_t len = s3.length();
    c = new char[len+1];
    strcpy(c,s.c_str());
    cout << c << len << endl;
    //如果是char的转换可以直接用strcpy
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值