c++读写文件

来源:互联网 发布:淘宝一阳指是什么 编辑:程序博客网 时间:2024/05/22 13:27

在代码里面有一个地方没有涉及到缓冲
强制缓冲可以通过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}
0 0
原创粉丝点击