首页 > 编程语言 > 详细

c++读写文件

时间:2017-04-29 19:31:06      阅读:245      评论:0      收藏:0      [点我收藏+]
#include <iostream>
#include <fstream>
#include <string>

int main()
{
    using namespace std;
    string filename;

    cout << "Enter name of new file:" << endl;
    cin >> filename;
    
    //type 1
    //ofstream fout(filename.c_str());
    
    //type 2
    ofstream fout;
    fout.open(filename.c_str()); //如果一个文件名被申明为“string”,那么就必须使用 “c_str”,然而,当你申明一个文件名为字符数组型,就没有必要使用/

    fout << "this is my test of file read and write \n" ;
    fout.close();

    //**********read*****************//
    ifstream fin(filename.c_str());
    char ch;
    // type 1
    //while (fin.get(ch))    //每次读取一个字符到ch
    //    cout << ch <<endl;
    
    //type 2
    fin >> ch;    // 读取一个字符 t
    string str;
    fin >> str; //读取 this
    cout << str << endl;

    //type 3
    //char ch2[100];
    //fin.getline(ch2,100);
    //int i = 0;
    //while(i<40)
    //{
    //    cout << "ch2[" << i << "]:" <<ch2[i]<< endl;
    //    i++;
    //}
    
    //type 4
    //string buff;
    //getline(fin,buff);
    //cout<<buff<<"\n\n";
    //cout << "Done\n";

    return 0;
}

 

c++读写文件

原文:http://www.cnblogs.com/shaogang/p/6785897.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!