码迷,mamicode.com
首页 > 编程语言 > 详细

C++文件流操作

时间:2015-05-11 14:22:39      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:

1.写文件

ofstream outfile("file_name",open_mode);

打开模式可以缺省,此时默认每次都是擦除文件中的原始数据,然后再写入此次的内容;

追加内容采用:ios_base::app

ofstream outfile("out_file.txt",ios_base::app);
if (!outfile)
    cerr << "Oops! Unable to save data!" << endl;
else
    outfile << "username" <<  
    << 18<<  
    << 18<< endl;

 2.读文件

ifstream infile("file_name",open_mode);
    ifstream infile("out_file.txt");
    string user_name;
    int nc_all;
    int nc_rgt;

    while (infile >> user_name)
    {
        infile >> nc_all >> nc_rgt;
        if (user_name == "username")
        {
            cout << "Welcome " << user_name << " back!" << endl;
            cout << "Your current score is " << nc_rgt << " out of " << nc_all << " " << endl;
            cout << "Good Luck!" << endl;
        }
    }

3.读写同一个文件

fstream iofile("file_name",open_mode_1|open_mode_2);

对同一个文件进行读写,要特别注意当文件为添加模式时,文件流指针位于文件末尾,要及时修改文件流指针的位置(seekg()函数)

    fstream iofile("test.txt",ios_base::app|ios_base::in);
    if (!iofile)
        cerr << "Oops! Unable to open the file!" << endl;
    else
    {
        cout << "Success!" << endl;
        iofile << "test" <<   << "100" <<   << "100" << endl;

        iofile.seekg(ios::beg);
        string user_name;
        string right;
        string all;
        while (iofile >> user_name)
        {
            iofile >> right >> all;
            cout << "Your name is " << user_name << endl;
            cout << "Your score is " << right << " out of " << all << endl;
        }
    }

C++文件流操作

标签:

原文地址:http://www.cnblogs.com/acode/p/4494278.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!